Reputation: 73
I'm trying to make a program that writes to a file, and reads it, then finds the average:
public static void main(String[] args) throws IOException {
writeToFile("C:\\scores.txt");
}
public static void writeToFile (String filename) throws IOException {
BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));
Scanner sc = new Scanner(System.in);
int i=0;
int q=0;
while(i >=0&&q<=20) {
System.out.print("Enter Grade:");
i=sc.nextInt();
outputWriter.write(i);
outputWriter.newLine();
q++;
}
outputWriter.flush();
outputWriter.close();
processFile(filename);
}
public static void processFile (String filename) throws IOException, FileNotFoundException {
try (BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)))) {
String line;
int lines=0;
int intValue= 0;
int sum = 0;
while (( line = inputReader.readLine()) != null){
intValue = Integer.parseInt(line);
String sumStr;
while((sumStr = inputReader.readLine()) != null) {
sum = Integer.parseInt(sumStr);
intValue = sum + intValue;
lines++;
}
intValue=sum+intValue;
}
System.out.println(intValue/lines);
inputReader.close();
}
}
}
Issue is, when I run this, it gets to the 21st grade(Supposed to end at 20) and gives me this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at scorereaderwriter.ScoreReaderWriter.processFile(ScoreReaderWriter.java:48)
at scorereaderwriter.ScoreReaderWriter.writeToFile(ScoreReaderWriter.java:34)
at scorereaderwriter.ScoreReaderWriter.main(ScoreReaderWriter.java:18)
Java Result: 1
What am I doing wrong here?
Upvotes: 0
Views: 52
Reputation: 36
Your program fails as soon as it attempts to run parseInt
, because your inputReader.readLine()
is returning nothing. What you could do is use inputReader.read()
to get the integer value.
So for example:
int sum = 0;
while((sum = inputReader.read()) != -1) {
intValue = sum + intValue
}
This should save you from having to read the file, convert the integer to string, then convert back to an integer again.
Edit: Also, check your first while loop, it runs 21 times instead of 20.
Upvotes: 1