java.io.EOFException being thrown - java

This code is throwing an java.io.EOFException, and I am not sure why this is happening.
import java.io.*;
class ReadInts {
public static void main(String[] args) {
String fileName = "intData.dat";
int sum = 0;
try {
DataInputStream instr = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
while (true) {
sum += instr.readInt();
System.out.println("The sum is: " + sum);
sum += instr.readInt();
System.out.println("The sum is: " + sum);
sum += instr.readInt();
System.out.println("The sum is: " + sum);
sum += instr.readInt();
System.out.println("The sum is: " + sum);
instr.close();
}
} catch (EOFException e) {
System.out.println("EOF reached for: " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("File " + fileName + " not found.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Problem reading " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
The contents of the input file is:
0
1
255
-1
There is no return character of line feed after -1.
The output I receive is:
The sum is: 805974282
The sum is: 1648322068
EOF reaced for: intData.dat
null
java.io.EOFException
at java.io.DataInputStream.readInt(DataInputStream.java:392)
at ReadInts.main(ReadInts.java:18)
The output is completely unexpected, and I assume the exception is being thrown because, for whatever reason, the value of sum is great than the maximum value of an int.
I tried changing "int sum = 0" to "long sum = 0" and received the same results.
I commented out the following:
sumOfInts += instr.readInt();
System.out.println("The sum is: " + sumOfInts);
sumOfInts += instr.readInt();
// System.out.println("The sum is: " + sumOfInts);
// sumOfInts += instr.readInt();
// System.out.println("The sum is: " + sumOfInts);
// sumOfInts += instr.readInt();
After doing this, I received the following exception:
The sum is: 805974282
The sum is: 1648322068
Problem reading intData.dat
Stream closed
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)
at java.io.BufferedInputStream.read(BufferedInputStream.java:269)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at ReadInts.main(ReadInts.java:14)
If it helps, I am using Ubuntu 18.04 LTS.
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Thanks for any help.
Tony

The problem is that readInt is not reading a string and convert the string to a number; it
reads four input bytes and returns an int value which it calculates using binary arithmetic.
0, \n(13), 1, \n(13) is 1st readInt
2, 5, 5, \n(13) is 2nd readInt
2 is third readInt after which you will get EOF exception
One more suggestion would be to close objects like stream in finally block
public static void main(String[] args) throws Exception {
String fileName = "C:\\rsc\\intdat.dat";
int sum = 0;
DataInputStream instr=null;
try {
instr = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
while (instr.available()!=0) {
sum += Integer.parseInt(instr.readLine());
System.out.println("The sum is: " + sum);
}
} catch (EOFException e) {
System.out.println("EOF reached for: " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("File " + fileName + " not found.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Problem reading " + fileName);
System.out.println(e.getMessage());
e.printStackTrace();
}
finally{
if(instr!=null)
instr.close();
}
}
PS: InputStream is a binary construct. If you want to read text data use BufferedReader instead

DataInputStream reads input as bytes in chunk of 4.
So,
0
1
255
-1
0, \n, 1, \n is one readInt
2, 5, 5, \n is other readInt
-1 is third readInt
So, after three readInt, you will get EOF exception as file has been finished.
Also, you should correct out wile loop.

Related

How to add the bonus?

I have done a code, which reads a file consists a number of employees, salary, and their rankings, based on their rankings how can we add the bonus percent to their salary...
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
double bonus;
if(phrases.contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(phrases.contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
It outputs:
Jame 900000 1
Bonus: 0.0
Jane 60000 2
Bonus: 0.0
Don 866000 3
Bonus: 0.0
I have no idea why
If you have an employeeBonus.txt file like below.
Jame 900000 2
Jane 60000 1
Don 866000 3
I think you will have three tokens as a string so, you can use a stringtokenizer class in order to get a salary and a grade.
At the first line of file is
Jame 900000 2
and the result of encoded string was
Jame%20%20%20%20900000%092
I've finally found the content of text file was mixed with a space and tab character by URL encoding.
So, the usage of this type is as follows,
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
It takes a salary and an identifier of bonus value from third and second token.
name = stTok.nextToken(); //first token
salary = Integer.valueOf(stTok.nextToken()).intValue(); //second token
grade = stTok.nextToken();
[source code]
package com.tobee.tests.inout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class CheckBounsFromFile {
public static void main(String[] args) {
String name, phrase, grade;
double bonus = 0;
int salary = 0;
BufferedReader readFile = null;
try {
readFile = new BufferedReader(new FileReader("resource/aa/employeeBonus.txt"));
while ((phrase = readFile.readLine()) != null) {
//System.out.println(phrase);
StringTokenizer stTok = new StringTokenizer(phrase, " \t");
name = stTok.nextToken();
salary = Integer.valueOf(stTok.nextToken()).intValue();
grade = stTok.nextToken();
if(grade!= null && !grade.equals(""))
{
if (grade.equals("1")) {
bonus = salary / 0.03;
} else if (grade.equals("2")) {
bonus = salary / 0.08;
} else if (grade.equals("3")) {
bonus = salary / 0.20;
}
System.out.printf("name[%s]salary[%d]Bonus[%f] \n",name, salary, bonus);
}
}
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
finally
{
try {
readFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
[result]
name[Jame]salary[900000]Bonus[30000000.000000]
name[Jane]salary[60000]Bonus[750000.000000]
name[Don]salary[866000]Bonus[4330000.000000]
Have a nice day.
The other answers appear to not cater for the fact that your salary variable is always 0, thus, your bonus calculation, which depends on your salary value will always be 0.
Assuming that this: Jame 900000 1 is a sample line from your text file, there are various issues with your code.
The first issue is this: (phrases.equals("1"). If phrase will be equal to the text in the current line you are processing: Jame 900000 1, this statement (and the same for the other two) will never return true, thus the bonus will never be calculated.
The second issue is that you are never extracting the salary value.
You will need to replace this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
if(phrases.equals("1")){
With something like this:
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
String[] employeeData = phrases.split("\\t"); //This assumes that your data is split by tabs.
salary = Double.parse(employeeData[1]);
if("1".equals(employeeData[2])) {
bonus = salary * 0.03;
}
...
You check the condition with equals method but your phrases variable contains different value rather than 1,2,3 that's why you get the bonus 0.
if(phrases.contains("1")){
bonus=salary/0.03;
}else if(phrases.contains("2")){
bonus=salary/0.08;
}else if(phrases.contains("3")){
bonus=salary/0.20;
}
or you can get the last parameter with:
phrases.substring(phrases.length()-1, phrases.length())
you can get the third parameter using contains or split method.
Please check this tutorial: https://www.tutorialspoint.com/java/java_string_split.htm
And one more thing your salary is always zero (0). please correct it
I have posted full code here:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class SubClass{
public static void main(String[] args) {
String phrases;
int salary=0;
try {
FileReader in = new FileReader("bonus.txt");
BufferedReader readFile = new BufferedReader(in);
while ((phrases = readFile.readLine()) != null) {
System.out.println(phrases);
phrases = phrases.trim().replaceAll("[ ]{2,}", " ");
String splitStr [] = phrases.split(" ");
double bonus;
salary = Integer.parseInt(splitStr[1]);
if(splitStr[2].contains("1")){
bonus=salary/0.03;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("2")){
bonus=salary/0.08;
System.out.println("Bonus: " + bonus);
}else if(splitStr[2].contains("3")){
bonus=salary/0.20;
System.out.println("Bonus: " + bonus);
}
// System.out.println();
}
readFile.close();
in.close();
}catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}

NumberFormatException for 2 textfields java

I was wondering how you would go about outputting which of the two text boxes is holding the NumberFormatException.
try
{
num1Convert = Integer.parseInt(num1Str);
num2Convert = Integer.parseInt(num2Str);
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
}
catch(NumberFormatException nfe)
{
errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer");
num1.requestFocus();
}
my program compares two numbers, and then returns the value of the numbers added together, but I need to output which of the two textareas are throwing back the exception, but I don't know how to do this. I have wrote within the code where it is necessary to output it.
How about this :
try{
num1Convert = Integer.parseInt(num1Str);
}
catch(NumberFormatException nfe) {
System.out.println("Exception in num1");
}
try{
num2Convert = Integer.parseInt(num2Str);
} catch(NumberFormatException nfe) {
System.out.println("Exception in num2");
}
//EDIT
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
Something like this should do:
String currentString = "";
try
{
currentString = num1Str;
num1Convert = Integer.parseInt(num1Str);
currentString = num2Str;
num2Convert = Integer.parseInt(num2Str);
sumValue = num1Convert + num2Convert;
sumLabel.setText(sumText + Integer.toString(sumValue));
}
catch(NumberFormatException nfe)
{
// errorLabel.setText((HERE IS WHERE I NEED TO PUT CODE TO SAY WHICH TEXTFIELD IT IS" must be an integer");
errorLabel.setText(currentString + " must be an integer");
num1.requestFocus();
}

storing and retreiving data from an Array, export to text file

I'm new to java and learning as I go, I'm currently working on arrays, I seem to be at a loss as to what I'm doing wrong here. I do not think it is pulling the data in the correct way, this program is suppose to read data from a text file, and ask the user for additional inputs, then display a report. I seem to be having issues with the donation output bits, as I have not gotten it to work once... The program dose compile and run, netbeans says its all green except for the bits of disabled code below for the display method. Any suggestions, comments and points in the right direction are greatly appreciated =)
Also could use some advice on getting the decimal places to line up all together for both the text file output and program display output.
The main class
import java.util.Scanner;
public class MyEventManager
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.printf("\nI will read a text file then add it with user "
+ "inputs in \norder to display and export a report detailing "
+ "an event.\n\n");
boolean startOver = false;
if (startOver == false) //enter loop
{
do
{
//ticket price
System.out.printf("What is the single ticket price for "
+ "the event? ");
double singleTicket = keyboard.nextDouble();
//maximum number of donations
System.out.printf("What is the maximum number of donations "
+ "expected for the event? ");
int maxDonations = keyboard.nextInt();
//create a new object for event class
MyEventClass myEvent = new MyEventClass(singleTicket,
maxDonations);
if (myEvent.fruityLoops == false)
do
{
myEvent.readAllData();
}
while (myEvent.fruityLoops != true);
myEvent.displayResults();
System.out.printf("\nWould you like to run program again? "
+ "[Y/N] - ");
String questionAskLoop = keyboard.next();
if ("N".equalsIgnoreCase(questionAskLoop))
{
startOver = true; //sets exit condition to end program...
}
}
while(startOver != true);
}
}
}
The second class
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class MyEventClass
{
private final double TICKET_PRICE;
private final int []moneyDonated;
private double totalTicketsSold;
private int DONATION_ARRAY_SIZE;
private int storedAmountDonations;
private double moneySpent;
boolean fruityLoops;
private boolean donationSuccess;
public static char amountType;
public static double amount;
public MyEventClass (double singleTicket, int maxDonations)
{
this.moneyDonated = new int[]{DONATION_ARRAY_SIZE};
this.fruityLoops = false;
this.TICKET_PRICE = singleTicket;
this.DONATION_ARRAY_SIZE = maxDonations;
this.moneySpent = 0;
}
public boolean myDonation (double donationAmount, int[] moneyDonated)
{
if (storedAmountDonations == DONATION_ARRAY_SIZE)
{
return false;
}
else
{
moneyDonated[storedAmountDonations] = (int) donationAmount;
storedAmountDonations++;
return true;
}
}
public void addNewTickets (double addedTickets)
{
totalTicketsSold += (int) addedTickets;
}
public double getTicketSales ()
{
return totalTicketsSold;
}
public double getTicketEnd ()
{
double ticketEnd = totalTicketsSold * TICKET_PRICE;
return ticketEnd;
}
public int [] getMoneyDonated (int[] moneyDonated)
{
//Calculate and return the total amount of money donated
return moneyDonated;
}
public int storedAmountDonations ()
{
return storedAmountDonations;
}
public double getMoneySpent ()
{
return moneySpent;
}
public void sortMethod (char amountType, double amount)
{
if(amount <= 0) //positive amount check
{
throw new IllegalArgumentException("Error Code B-90: Invalid amount "
+ "(not over 0) -- line: " + amountType + " " + amount
+ " ignored");
}
else if (amountType == 'T' || amountType == 't') //tickets
{
addNewTickets(amount);
}
else if (amountType == 'D' || amountType == 'd') //donations
{
myDonation(amount, moneyDonated);
if (donationSuccess == false) //checks if array is full
{
throw new ArrayIndexOutOfBoundsException ("Error code B-103: "
+ "The array is full " + amount + " will not be stored"
+ " in the array");
}
}
else if (amountType == 'E' || amountType == 'e') //amount spent
{
moneySpent += amount;
}
else
throw new IllegalArgumentException("Error Code B-113: Invalid item "
+ "type (not T, D, or E) -- line: " + amountType + " "
+ amount + " ignored");
}
public void readAllData()
{
int lineCount = 0;
Scanner keyboard = new Scanner( System.in );
System.out.printf("\nPlease input the file location: ");
String readFile = keyboard.next();
try
{
File inputFile = new File (readFile);
Scanner scanFile;
scanFile = new Scanner( inputFile );
System.out.println("Reading data file....");
while (scanFile.hasNext())
{
amountType = scanFile.next().charAt(0);
amount = scanFile.nextDouble();
lineCount++;
try
{
sortMethod(amountType, amount);
}
catch (IllegalArgumentException a)
{
System.out.printf("\nError code B-145: An error occured "
+ "while attempting to add the data from file");
}
catch (ArrayIndexOutOfBoundsException b)
{
System.out.printf("\nError code B-150: An error occured "
+ "while attempting to add to the array.");
}
}
scanFile.close();
System.out.printf("\nThe total amount of readable lines where "
+ lineCount + " lines.\n\n");
}
catch (FileNotFoundException c)
{
System.out.printf("\nError code B-160: The file " + readFile
+ " was not found!\n");
fruityLoops = false; //restart program
}
fruityLoops = true; //contuine on with program
}
public int getLowest (int[] moneyDonated)
{
int lowValue = moneyDonated[0];
for(int i=1;i < moneyDonated.length;i++)
{
if(moneyDonated[i] < lowValue)
{
lowValue = moneyDonated[i];
}
}
return lowValue;
}
public double getAverage(int[] moneyDonated)
{
int sum = moneyDonated[0];
for(int i=1;i < moneyDonated.length;i++)
sum = sum + moneyDonated[i];
double advValue = sum / moneyDonated.length;
return advValue;
}
public int getHighest (int[] moneyDonated)
{
int maxValue = moneyDonated[0];
for(int i=1;i < moneyDonated.length;i++)
{
if(moneyDonated[i] > maxValue)
{
maxValue = moneyDonated[i];
}
}
return maxValue;
}
public void displayResults()
{
double income = 0;//moneyDonated + ticketEnd;
double profits = income - moneySpent;
Scanner keyboard = new Scanner ( System.in );
System.out.printf("\nWhere is the file for the report export? ");
String reportFile = keyboard.next();
try
{
File outputFile = new File (reportFile);
Scanner scanFile = new Scanner (outputFile);
System.out.println("Generating output data file....");
try (BufferedWriter writer =
new BufferedWriter(new FileWriter(outputFile)))
{
writer.write("Event Overall Outcome:");
writer.newLine();
writer.write("Ticket Price %15.2f" + TICKET_PRICE);
writer.newLine();
writer.newLine();
writer.write("Donation Analysis:");
writer.newLine();
writer.write("Lowest donation " + getLowest (moneyDonated));
writer.newLine();
writer.write("Adverage donation " + getAverage (moneyDonated));
writer.newLine();
writer.write("Highest donation " + getHighest(moneyDonated));
writer.newLine();
writer.newLine();
writer.write("Profit/Loss Results:");
writer.newLine();
writer.write(totalTicketsSold + "Tickets sold" + getTicketEnd());
writer.newLine();
writer.write(storedAmountDonations() + " Donations "
+ Arrays.toString(moneyDonated) + " +");
writer.newLine();
writer.write(" --------");
writer.newLine();
writer.write("Total Income " + "%14.2f" + income);
writer.newLine();
writer.write("Total Expenses " + "%12.2f" + " -" + moneySpent);
writer.newLine();
writer.write(" --------");
writer.newLine();
if (profits < 1)
{
writer.write(" Event Losses " + "%13.2f " + profits);
}
else
{
writer.write(" Event Profits " + "%13.2f " + profits);
}
writer.flush();
writer.close();
}
catch (IOException d)
{
System.out.printf("\nError code B-280: There was an error "
+ "while attempting to write to " + reportFile
+ "\nThe file may be damaged!");
}
System.out.printf("\nOutput Success!");
}
catch (FileNotFoundException d)
{
System.out.printf("\nError code B-288: The file " + reportFile
+ " could not be opened! The report cannot be generated.\n");
}
System.out.printf("\nEvent Overall Outcome:");
System.out.printf("\n\n Ticket Price %15.2f", TICKET_PRICE);
System.out.printf("\n\n Donation Analysis: ");
/*System.out.printf("\n Lowest donation " + "%10.2f",
getLowest (moneyDonated));
System.out.printf("\n Adverage donation " + "%10.2f",
getAverage (moneyDonated));
System.out.printf("\n Highest donation " + "%10.2f",
getHighest(moneyDonated));*/
System.out.printf("\n\n Profit/Loss Results: ");
System.out.printf("\n " + totalTicketsSold + " Tickets sold "
/*+ "%3.2f"*/ + getTicketEnd());
System.out.printf("\n " + storedAmountDonations() + " Donations "
/* + "%3.2f"*/ + Arrays.toString(moneyDonated) + " +");
System.out.printf("\n --------");
System.out.printf("\n Total Income " + "%14.2f", income);
System.out.printf("\n Total Expenses " + "%12.2f" + " -", moneySpent);
System.out.printf("\n --------");
if (profits < 1)
{
System.out.printf("\n Event Losses " + "%13.2f \n\n", profits);
}
else
{
System.out.printf("\n Event Profits " + "%13.2f \n\n", profits);
}
}
}
This is the text file input
T 25
E 210.99
T 1
D 500.00
E 134.67
D 1
This is text file output
Event Overall Outcome:
Ticket Price %15.2f60.0
Donation Analysis:
Lowest donation 500
Adverage donation 500.0
Highest donation 500
Profit/Loss Results:
26.0Tickets sold1560.0
1 Donations [500] +
--------
Total Income %14.2f0.0
Total Expenses %12.2f -345.65999999999997
--------
Event Losses %13.2f -345.65999999999997
And lastly this is what the program displays to the screen...
run:
I will read a text file then add it with user inputs in
order to display and export a report detailing an event.
What is the single ticket price for the event? 25
What is the maximum number of donations expected for the event? 2
Please input the file location: event.txt
Reading data file....
Error code B-150: An error occured while attempting to add to the array.
Error code B-150: An error occured while attempting to add to the array.
The total amount of readable lines where 6 lines.
Where is the file for the report export? export.txt
Error code B-288: The file texport.txt could not be opened! The report
cannot be generated.
Event Overall Outcome:
Ticket Price 25.00
Donation Analysis:
Profit/Loss Results:
26.0 Tickets sold 650.0
1 Donations [500] +
--------
Total Income 0.00
Total Expenses 345.66 -
--------
Event Losses -345.66
Would you like to run program again? [Y/N] -
Just as an FYI, for my exception error codes A is the main class and B is the second class, the number the follows is the line of code the message came from. Just something I was trying to help me find my place faster...
My goal is to get the display to look like this.
Your main issue is in your second class:
this.moneyDonated = new int[]{DONATION_ARRAY_SIZE};
This is not creating an array of size DONATION_ARRAY_SIZE.
Proper syntax is:
this.moneyDonated = new int[DONATION_ARRAY_SIZE];
There are 2 critical issues above. Firstly the size of the array. You should have something like this:
this.DONATION_ARRAY_SIZE = maxDonations;
this.moneyDonated = new int[DONATION_ARRAY_SIZE];
Secondly, the donationSuccess boolean will be initialised to false. And you have this block of code:
if (donationSuccess == false) //checks if array is full
{
throw new ArrayIndexOutOfBoundsException ("Error code B-103: "
+ "The array is full " + amount + " will not be stored"
+ " in the array");
}
You never change that donationSuccess value hence that block of code will always throw that error even though it is not the case. You should rethink the way you initialise and set the donationSuccess value.

Saving the result to file - JAVA

I have a very stupid problem... I cannot get know how to save the results in output file that second array is save in a lower line.
This is how it saves:
dist[0 10 13 10 6 18 ] pred[-15 2 5 1 4 ]
I want it to save like this:
dist[0 10 13 10 6 18 ]
pred[-15 2 5 1 4 ]
CODE:
try{
outputFile = new File("Out0304.txt");
out = new FileWriter(outputFile);
out.write("\n" + "dist[");
out.write("\n");
for (Top way : tops){
out.write(way.shortest_path + " ");
}
out.write("]\n");
out.write("\n");
out.write("\n" + "pred[");
for (Top ww : tops){
if (ww.previous != null) {
out.write(ww.previous.number + " ");
}
else{
out.write("-1");
}
}
out.write("] \n ");
out.close();
}
catch (IOException e){
System.out.println("Blad: " + e.toString());
}
}
}
In Windows you need "\r\n" for new line
You can use the following to write to file:
PrintWriter pw = new PrintWriter(new FileWriter("fileName"),true);
pw.println("[");
for(int i=0;i<pred.length;i++)
{
pw.println(pred[i]+" ");
}
pw.println("]");
pw.close();

File Input Java Mac

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.

Categories

Resources