File Input Java Mac - java

I'm writing up a program that goes into a basic .txt file and prints certain things. It is a comma-delimited file. The file includes 7 first and last names, and also 4 numbers after. Each of the seven on a separate line.
Each line looks like this:
George Washington, 7, 15, 20, 14
The program has to grab the last name and then average the 4 numbers, but also average the first from all seven, second from all seven, etc. I'm not sure on how to start approaching this and get it to keep grabbing and printing what's necessary. Thanks for any help. I appreciate it. I'm using a Mac to do all of this programming and it needs to run on Windows so I'm using :
File Grades = new File(System.getProperty("user.home"), "grades.txt");
so how would I use that to read from the file?

Java's File class doesn't actually handle the opening or reading for you. You may want to look at the FileReader and BufferedReader classes.

Don't worry about whether it's running on Mac or Windows. Java takes care of all the business for you. :)
You could do something like the following. It's just a quick solution so you might want to do some changes perhaps. It reads from a file named "input.txt" right now.
import java.io.*;
public class ParseLines {
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("input.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(new DataInputStream(fs)));
String line;
double collect[] = {0.0, 0.0, 0.0, 0.0};
int lines = 0;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
if (parts.length == 5) {
int avg = 0;
boolean skip = false;
for (int i = 1; i < 5; i++) {
String part = parts[i].trim();
try {
int num = Integer.valueOf(part);
avg += num;
collect[i - 1] += (double) num;
}
catch (NumberFormatException nexp) {
System.err.println("Input '" + part +
"' not a number on line: " + line);
skip = true;
break;
}
}
if (skip) continue;
avg /= 4;
lines++;
System.out.println("Last name: " + parts[0].split(" ")[1] +
", Avg.: " + avg);
}
else {
System.err.println("Ignored line: " + line);
}
}
for (int i = 0; i < 4; i++) {
collect[i] /= (double) lines;
System.out.println("Average of column " + (i + 1) + ": " +
collect[i]);
}
reader.close();
} catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Edit: Altered the code to average the first, second, third and fourth column.

Related

trying to convert a string array to a double and produce a total price [duplicate]

This question already has answers here:
Convert String to double in Java
(14 answers)
Closed 1 year ago.
So ive got my text file which is seperated as so:
Title - Author - Price - Publisher - ISBN (it needs to be like this)
and what I want to do is get all of the price values out of this text document:
Windows XP - Graham Winter - 32.50 - O'Reilly - 0471974555
Windows XP Unwired - Wei Meng Lee - 24.95 - O'Reilly - 0596005369
CCDA Exam Guide - Anthony Bruno - 49.95 - Cisco Press - 0735700745
Multimedia Comms - Fred Halsall - 53.99 - Addison Wesley - 0201398184
Guide to Networks - Tamara Dean - 34.50 - Course Tech - 1439055661
802.11 Security - Jon Edney and William Hal - 68.99 - Addison Wesley - 0321136209
Wireless Hacks - Rob Weeks - 29.50 - O'Reilly - 0596101442
Large Scale LANs - Kevin Dooley - 39.00 - O'Reilly - 0596001509
Learning Java - William Lane -12.00 - Wiley - 0811234561
This code is what I have so far but I am really stuck as to how to get the total values from the splitArray[2] which is a string type.
import java.io.File;
import java.util.Scanner;
import java.io.IOException;
public class Part_2 {
private static int count;
public static void main(String[] args){
int D = 0;
String line = "";
int num = 0;
Scanner keyboard = new Scanner (System.in);
{
// Allow the user to enter the name of text file that the data is stored in
System.out.println("Type in name of the file");
String fileName = keyboard.nextLine();
File Fileobject = new File (fileName);
{
if (!Fileobject.exists())
{
System.out.println("Error - File does not exist");
System.exit(0);
}
try {
count = 0;
if (count < 5)
{
Scanner fileReader = new Scanner (Fileobject);
System.out.println("\n"+String.format("%-30s", "Title") +
String.format("%-25s", "Author") +
String.format("%-25s", "Price") +
String.format("%-25s", "Publisher") +
String.format("%-25s", "ISBN"));
System.out.println(String.format("%-30s", "=====")+
String.format("%-25s", "=====")+
String.format("%-25s", "=====")+
String.format("%-25s", "======")+
String.format("%-25s", "===="));
while(fileReader.hasNext())
{
line = fileReader.nextLine();// Read a line of data from text file
num = num +1;
// The format of each line of data in the text file is as follow:
// Title - Author - Price - Publisher - ISBN
// Need to split each line read from file before can process it
try {
String [] splitArray = line.split("-");
// check to make sure there are 4 parts in splitArray
if(splitArray.length == 4)
{
// remove spaces
splitArray[0] = splitArray[0].trim();
splitArray[1] = splitArray[1].trim();
splitArray[2] = splitArray[2].trim();
splitArray[3] = splitArray[3].trim();
splitArray[4] = splitArray[4].trim();
}
if (splitArray[0].isEmpty())
{
D++;
}
if (splitArray[1].isEmpty())
{
D++;
}
if (splitArray[2].isEmpty())
{
D++;
}
if (splitArray[3].isEmpty())
{
D++;
}
if (splitArray[4].isEmpty())
{
D++;
}
System.out.println(String.format(" %-30s", splitArray[0])+
String.format(("%-25s"), splitArray[1])+
String.format(("%-25s"), splitArray[2])+
String.format(("%-25s"), splitArray[3])+
String.format(("%-25s"), splitArray[4]));
}
catch (Exception e) {
System.out.println("Line delimiter error");
D++;
}
}
System.out.println("");
System.out.println("totals");
System.out.println("-----------------------------");
System.out.println("The total number of books: ");
System.out.println("The total costs of books: ");
System.out.println("Maximum cost of a book: " );
System.out.println("Minimum cost of a book: " );
System.out.println("Average cost of a book: " );
System.out.println("there are " + D + " error(s) within the text document");
}
}
catch (IOException e) {
// IO error while reading from the file.
System.err.println("Error while reading from file ");
}
}
}
}
}
All of the data in the file gets split and then is put into the different arrays which are all string types, however this is a problem as I am trying to find the total price of all of the books.
Any help on this problem would be appreciated, I have tried multiple ways but I always seem to get back a null value or 0.0
In this example I have shown how to make a sum of Double values from String array. It might be helpful in your example:
double sum = 0;
String[] strings = "1 2 3 4 5 6".split(" "); // this is just an example, quick way to create array of Strings containing values that can be parsed to Doubles in next step.
for(int i = 0; i < strings.length; i++) {
Double d = Double.parseDouble(strings[i]);
sum += d;
}
System.out.println(sum);
I think the biggest issue is your assumption that there will be 4 elements in your five element line. if(splitArray.length == 4) is incorrect. I would also prefer using a split regular expression that consumed the white space in the separator. Also, you had a lot of anonymous and nested blocks. I would store all of the prices in a List and then use (assuming Java 8+) streams to determine the DoubleSummaryStatistics at the end. Something like,
int D = 0;
Scanner keyboard = new Scanner(System.in);
// Allow the user to enter the name of text file that the data is stored in
System.out.println("Type in name of the file");
String fileName = keyboard.nextLine();
File fileObj = new File(fileName);
if (!fileObj.exists()) {
System.out.println("Error - File does not exist");
System.exit(0);
}
List<Double> prices = new ArrayList<>();
try (Scanner fileReader = new Scanner(fileObj)) {
while (fileReader.hasNextLine()) {
String line = fileReader.nextLine();
String[] tokens = line.split("\\s*-\\s*");
if (tokens.length == 5) {
try {
prices.add(Double.valueOf(tokens[2]));
} catch (NumberFormatException nfe) {
System.out.println("Invalid price: " + tokens[2]);
D++;
}
} else {
System.out.println("Invalid number of tokens: " + line);
D++;
}
}
} catch (FileNotFoundException fnfe) {
System.out.println("Error - could not read file");
System.exit(0);
}
DoubleSummaryStatistics stats = prices.stream()
.mapToDouble(Double::doubleValue)
.summaryStatistics();
System.out.println("");
System.out.println("totals");
System.out.println("-----------------------------");
System.out.println("The total number of books: " + stats.getCount());
System.out.println("The total costs of books: " + stats.getSum());
System.out.println("Maximum cost of a book: " + stats.getMax());
System.out.println("Minimum cost of a book: " + stats.getMin());
System.out.println("Average cost of a book: " + stats.getAverage());
System.out.println("there are " + D + " error(s) within the text document");

how do I get data from a text file and save it into a string?

How do I get data from a text file and save it into a string?
For example, my text file has the numbers 1, 4, 5, 6, 8, and 10.4. These numbers can be on the same line or on separate lines. I want to concatenate them into a string, like so: 1 4 5 6 8 10.4
import java.io.File;
import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class f {
public static void main(String args[]) {
int count = 0;
double totalcount = 0;
double average = 0;
Scanner read = new Scanner(System.in);
Scanner file;
String input = "";
String test = "";
double[] array1 = new double[100];
while (true) {
System.out.println("Enter name of file or enter quit to exit");
input = read.next();
if (input.equalsIgnoreCase("quit")) {
break;
}
try {
file = new Scanner(new File(input));
if (!file.hasNextLine()) {
System.out.println(input + " file is empty");
}
while (file.hasNext()) {
totalcount = totalcount + file.nextDouble();
count++;
}
while (file.hasNext()) {
test = test + (" ") + file.next();
}
System.out.println("bla" + test);
average = totalcount / count;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println("\nCount: " + count);
System.out.println("Total: " + df.format(totalcount));
System.out.println("Average: " + df.format(average));
System.out.println();
} catch (FileNotFoundException e) {
System.out.println(input + " doesn't exist");
}
}
}
}
My code does not work correctly.
Your code is working fine, the problem is, you trying to access content of your file two times.after first while loop , the hasnext() method will return false.because you already accessed all the element in first while loop.
so it will not execute -
while (file.hasNext()) {
test = test + (" ") + file.next();
}
Other than that your code is fine.
if you want store it in string also then do small modification in your first while loop as below-
while (file.hasNext()) {
Double d=file.nextDouble();
test = test + (" ")+d;
totalcount = totalcount + d;
count++;
}
I think this will give you what you want.
Hello i think below code will be useful for you ,as per your question i have txt file with data , first i am getting the location of file & then i am trying to get the content , at last i am printing it to the console
File f = new File("D:\\temp.txt");
String content11 = FileUtils.readFileToString(f);
System.out.println(content11);

Java File Problems

So we want an application to allow the user to enter the names and grades of students the user should be prompted for the name of the file to create and for the number of students to be entered (1 grade per student). Then the program takes all of the grades and averages them. The problem is that it is not reading the file and always gives us a average of -0.0.
`
public static void main(String[] args) throws IOException {
System.out.println("What is the name of the file you would like to create?");
filename = p.next();
File fd = new File(filename + ".txt");
fd.createNewFile();
students(fd);
}
public static void students(File fd) throws IOException {
int numbstudents;
FileWriter ap = new FileWriter(fd, true);
BufferedWriter ad = new BufferedWriter(ap);
System.out.println("How many students would you like to add?");
numbstudents = p.nextInt();
int i = 0;
while (i != numbstudents) {
for (i = 0; i < numbstudents; i++) {
System.out.println("What is the name of student number " + i + " ?");
String name = p.next();
ad.write(name);
ad.newLine();
System.out.println("What grade did student number " + i + " acheive?");
String a = f.next();
ad.write(a);
ad.newLine();
}
}
read(fd);
ad.close();
}
public static void read(File fd) throws FileNotFoundException {
int counter = 0;
FileReader h;
BufferedReader g;
String test;
double average, total = 0;
int number = 0;
int i = 0;
try {
h = new FileReader(fd);
g = new BufferedReader(h);
while ((test = g.readLine()) != null) {
number += 1;
System.out.println(test);
counter = counter + 1;
i = counter % 2;
if (i == 0) {
total += Double.parseDouble(test);
}
}
average = total / (number - 1);
System.out.println("The students average is: " + average);
g.close();
fd.delete();
} catch (FileNotFoundException e) {
System.out.println("File could not be found.");
} catch (IOException e) {
System.out.println("Your file could not be read.");
}
}
}
`
You're attempting to read from the file before you've closed the writer.
The close() call includes flushing buffered data to disk. You're reading before data is flushed to disk.
As a side note, consider what you're accomplishing with this pair of statements:
while (i != numbstudents) {
for (i = 0; i < numbstudents; i++) {
The while is unnecessary. The for statement iterates over the comfortably numb students.
Also note the difference in conditions between the two. In general, when iterating over numbers, it's safer to use '<', '<=', '>' or '>=' than '==' or '!='. Otherwise, if you pass by the endpoint before an equality condition, it will continue happily past the end.
Finally, consider naming your methods with descriptive verb phrases. This will help you with breaking the big problem down into smaller pieces. For example, you could have one method called inputStudents() that reads input and creates and closes the file, called before another method printAverageOfStudents() that reads the file and computes the average.

OutOfBoundsException When Calling Return For A Method JAVA

i'll get straight to the chase. If a user wants to read another file they must type r in the menu, then they are thrown with a return readFile(); method which takes them to the top of the program and asks them the same question it did at the beggining when they first ran this program. Only issue is when you type R or Default it throws an OutOFBoundsException. BTW It is Reading a CSV file
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000
at studentrecs.StudentRecs.in(StudentRecs.java:71)
at studentrecs.StudentRecs.readFile(StudentRecs.java:55)
at studentrecs.StudentRecs.menu(StudentRecs.java:97)
at studentrecs.StudentRecs.main(StudentRecs.java:33)
Java Result: 1
/
public static Boolean readFile(String filename) throws IOException { //Constructor for filename
try {
Scanner userInput = new Scanner(System.in);
System.out.println("Type R To Read a File or Type Default for the default file");
user = userInput.nextLine();
if (user.equalsIgnoreCase("r")) {
user = userInput.nextLine();
}
filename = user;
if (user.equalsIgnoreCase("default")) {
filename = "newreg2.csv";
}
Scanner input = new Scanner(new FileReader(filename));
while (input.hasNext()) {
in(input.nextLine());
numstu++;
}
input.close();
return true;
} catch (IOException e) {
System.err.println(e.getMessage());
}
return false;
}
public static void in(String reader) {
String splitter[];
splitter = reader.split(",");
stu[numstu] = new StuRec();
stu[numstu].studentID = splitter[0];
stu[numstu].lastName = splitter[1];
stu[numstu].firstName = splitter[2];
stu[numstu].phoneNumber = splitter[3];
stu[numstu].courseCode = splitter[4];
stu[numstu].periodNumber = Integer.parseInt(splitter[5]); // parseInt turns a string of digits into an integer
stu[numstu].mark = Integer.parseInt(splitter[6]);
}
public static boolean menu() throws IOException {
String choice;
Scanner userInput = new Scanner(System.in);
System.out.println("=============================================");
System.out.println("Type R To Read Another File");
System.out.println("Type L To Print all File Records");
System.out.println("Type AA To Print The Average Of All The Marks");
System.out.println("Type X To Exit The Program");
choice = userInput.nextLine();
double average = 0.0; // declare average
if (choice.equalsIgnoreCase("L")) {
for (int i = 0; i < numstu; i++) {
System.out.println(stu[i].lastName + ", " + stu[i].firstName + ", " + stu[i].studentID + ", " + stu[i].phoneNumber + ", " + stu[i].courseCode + ", " + stu[i].periodNumber + ", " + stu[i].mark);
}
}else if (choice.equalsIgnoreCase("R")){
return readFile(filename);
} else if (choice.equalsIgnoreCase("AA")) {
for (int i = 0; i < numstu; i++) {
average += stu[i].mark; // keep adding to average
}
}else if (choice.equalsIgnoreCase("X")) {
for (int i = 0; i < numstu; i++) {
System.exit(i);
}
}else if (choice.equalsIgnoreCase("AC")) {
} else {System.err.println("Unknown Key Try Again...");
}
// divide by zero protection
if ( choice.equalsIgnoreCase("AA") && numstu > 0 ) {
average = average/numstu; // compute the average. Always use the size in terms of a variable whenever possible.
System.out.println(average); // as noted below, if this is an integer value, < #of students computations will eval to 0.
}
else if (!choice.equalsIgnoreCase("AA") && numstu < 0) {
System.out.println("Oops! No Marks To Calculate! :(");
}
return menu();
}
}
It looks like EITHER you have initialised numstu to start at 1, OR you have more than 1000 lines in your file.
The effect of either of these errors would be that you eventually attempt to write data to entry 1000 of stu. But since you've initialised stu with 1000 entries, numbered from 0 to 999, this gives your error.
You should make sure that numstu is initially 0, not 1.
And next time you post a question, post ALL of your code, not just the parts where you think the error might be. It's very difficult for most people to find bugs in code that they can't see.

display in table form

hi this is my code to calculate term frequency.
System.out.println("Please enter the required word :");
Scanner scan = new Scanner(System.in);
String word = scan.nextLine();
String[] array = word.split(" ");
int filename = 11;
String[] fileName = new String[filename];
int a = 0;
for (a = 0; a < filename; a++) {
try {
File file = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + a
+ ".txt");
System.out.println("File = abc" + a + ".txt");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
int totalCount = 0;
int wordCount = 0;
int numDoc2 = 0;
Scanner s = new Scanner(file);
{
while (s.hasNext()) {
totalCount++;
if (s.next().equals(array[i]))
wordCount++;
}
System.out.println("Word count: " + wordCount);
System.out.println("Total count: " + totalCount);
System.out.printf("Term Frequency: %8.4f",
(double) wordCount / totalCount);
System.out.println("\n");
}
}
} catch (FileNotFoundException e) {
System.out.println("File is not found");
}
}
so far the code display
Please enter the required word :
about
File = abc0.txt
about
Word count: 0
Total count: 1706
Term Frequency: 0.0000
File = abc1.txt
about
Word count: 0
Total count: 9819
Term Frequency: 0.0000
how do i create a data table form which is like this :
OUTPUT :
filename word total term
abc0.txt 0.1 0.2 0.3
abc1.txt 0.4 0.5 0.6
Instead of using System.out.println(String), use System.out.print(String).
System.out.print(String) will print out the data without causing the following System.out.print(String) to start on the next line. This will help you get the data output in the correct format
Change the print statement for the file name at the top to
System.out.print("abc" + a + ".txt");
AND Change the print statements at the end to
System.out.print(" " + wordCount);
System.out.print(" " + totalCount);
System.out.printf(" %8.4f", (double) wordCount / totalCount);
System.out.println();
You can use System.out.print(); in-place of System.out.println(); and provide proper TABs by "\t"
Example:
See difference in each case
System.out.print("Hello ");
System.out.print("World");
//output: Hello World
System.out.println("Hello ");
System.out.println("World");
//output:
Hello
World
Use System.out.format, it uses a Formatter internally.

Categories

Resources