Results 1 to 6 of 6
Thread: "Complex" File Reading
- 10-23-2013, 07:38 PM #1
Senior Member
- Join Date
- Aug 2013
- Location
- Sweden
- Posts
- 163
- Rep Power
- 7
"Complex" File Reading
This program down below reads a file which contains imaginary students' names and grades on tests, like this for example:
Made-up Person 1
5 4 4 3 4
Made-up Person 2
3 3 2 3 3
etc.
Anyway, I wanted my program to output every person's name and then the average of their scores/grades, but when when it read the scores to a two-dimensional array something went wrong on the second run of my main loop. I can't really tell why, can you guys? (The error is on line 18.)
Thanks!
This is the error by the way:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at hej.main(hej.java:18)Java Code:import java.util.Scanner; import java.io.*; public class hej{ public static void main(String[] args){ File file = new File("hej.txt"); String namn[] = new String[30]; int poäng[][] = new int[30][5], antal = 0, rad = 0; try{ Scanner cp = new Scanner(file); while(true){ int test = 0; String s = cp.nextLine(); if(s == null) break; namn[antal++] = s; for(int x=0;x<5;x++) poäng[rad][test++] = cp.nextInt(); System.out.println(namn[antal-1] + "'s average score: " + ((double)(poäng[rad][0] + poäng[rad][1] + poäng[rad][2] + poäng[rad][3] + poäng[rad][4])/5)); rad++; } }catch(FileNotFoundException e){ } } }
- 10-23-2013, 09:12 PM #2
Member
- Join Date
- Oct 2013
- Posts
- 4
- Rep Power
- 0
Re: "Complex" File Reading
Hi Zelaine,
I am a novice myself so this is only my best guess as to what your problem is.
I think you are getting an exception because you are attempting to read past the end of the file with your Scanner. I have modified your code below to fix it:
Java Code:import java.util.Scanner; import java.io.*; public class hej{ public static void main(String[] args){ File file = new File("hej.txt"); String namn[] = new String[30]; int poäng[][] = new int[30][5], antal = 0, rad = 0; try{ Scanner cp = new Scanner(file); while(cp.hasNextLine()){ //CHANGED -- Checks if the File has another input int test = 0; //consumes name line String s = cp.nextLine(); //removed null check as it it no longer necessary. namn[antal++] = s; for(int x=0;x<5;x++) poäng[rad][test++] = cp.nextInt(); System.out.println(namn[antal-1] + "'s average score: " + ((double)(poäng[rad][0] + poäng[rad][1] + poäng[rad][2] + poäng[rad][3] + poäng[rad][4])/5)); rad++; } }catch(FileNotFoundException e){ } } }
This code isn't very flexible, it only works for a file with exactly 30 students each who have exactly 5 scores. You may want to think about using a Collection type, like an ArrayList instead of a standard array. I've written my own version below with some comments to explain some of the choices I've made:
Java Code:import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /* Average Scores * -------------- * By Kramko * Takes a file in the following format: * * Student Name * testScore1 testScore2 testScore3 etc * * Calculates the average score and prints the * students name and average score * * Works with any number of students/scores * */ public class AverageScores { public static void main(String[] args) throws FileNotFoundException{ //file name is passed in as first argument //allows for different files to be processed after program is compiled File file = new File(args[0]); //you could replace this with a file path again if you needed to //Scanner to read file Scanner fileReader = new Scanner(file); while(fileReader.hasNextLine()){ //Checks if the File has another input //consumes name line String name = fileReader.nextLine(); //throws an exception if there isn't another line if(!fileReader.hasNextLine()) throw new Exception("File not properly formatted"); String scores = fileReader.nextLine(); //creates a new scanner to read the scores -- Scanners can read Strings! Scanner scoreReader = new Scanner(scores); double totalScore = 0; int numScores = 0; double averageScore; //checks to see if the next token can be read as a double while(scoreReader.hasNextDouble()) { //adds double to score totalScore += scoreReader.nextDouble(); //increment numScores numScores++; } //ensures the program doesn't divide by zero if (numScores <= 0) averageScore = 0; else averageScore = totalScore/numScores; //formats averageScore so that it only shows 2 decimal places System.out.println(name +"'s Average Score: " + String.format(".2f", averageScore)); scoreReader.close(); } fileReader.close(); } }
The advantage of this version is that it can process any number of students with any number of scores!
Again, I consider myself a novice as well, but I hope this helped!
EDIT: Don't forget to close your Scanners like I did before I edited this ;)Last edited by Kramko; 10-23-2013 at 10:02 PM. Reason: Forgot to close Scanners!
- 10-23-2013, 11:16 PM #3
Senior Member
- Join Date
- Aug 2013
- Location
- Sweden
- Posts
- 163
- Rep Power
- 7
Re: "Complex" File Reading
Thanks for your extensive help and a new perspective on solving the problem! :)
As you can see I decided not to use arrays at all since it seems like the purpose of your program is simply to print average scores.
BTW, what exactly does this mean? I can't run that part, the program gives me an error saying something about an "unhandled exception".
Java Code:if(!fileReader.hasNextLine()) throw new Exception("File not properly formatted");
Last edited by Zelaine; 10-23-2013 at 11:41 PM.
- 10-23-2013, 11:54 PM #4
Senior Member
- Join Date
- Aug 2013
- Location
- Sweden
- Posts
- 163
- Rep Power
- 7
Re: "Complex" File Reading
The String format only outputs ".2f" by the way, and your program doesn't read the scores at all, because it always outputs zero.
- 10-24-2013, 12:05 AM #5
Senior Member
- Join Date
- Aug 2013
- Location
- Sweden
- Posts
- 163
- Rep Power
- 7
Re: "Complex" File Reading
I did this instead though and now it works.
Java Code:import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class hej{ public static void main(String[] args) throws FileNotFoundException{ File file = new File("hej.txt"); Scanner fileReader = new Scanner(file); while(fileReader.hasNextLine()){ String name = fileReader.nextLine(); if(!fileReader.hasNextLine()) break; String scores = fileReader.nextLine(); Scanner stringToNumber = new Scanner(scores); int summa = 0, elements = 0; double average; while(stringToNumber.hasNextInt()){ summa += stringToNumber.nextInt(); elements++; } if(elements == 0) average = 0; else average = summa / elements; System.out.println(name + "'s average score was " + average + "!"); stringToNumber.close(); } System.out.println("Goodbye!"); fileReader.close(); } }
- 10-24-2013, 12:47 AM #6
Member
- Join Date
- Oct 2013
- Posts
- 4
- Rep Power
- 0
Re: "Complex" File Reading
Hi sorry for the confusion,
it should be:
Java Code:String.format("%.2f",averageScore);
As you only receiving 0 as the average score -- I'm not quite sure why that is happening for you. I have run the program on my machine and it seems to be operating correctly.
The only change I made from my earlier posting is adding the "%" to the String.format call.
Similar Threads
-
Reading from a File, ArrayList and "reference"
By pokadean in forum New To JavaReplies: 5Last Post: 09-12-2013, 10:03 PM -
access denied("java.net.SocketPermission" "127.0.0.1:1099" "connect,resolve")
By klspepper in forum New To JavaReplies: 0Last Post: 12-07-2012, 09:29 AM -
Convert string operation symbols "+", "-", "/", "*" etc.
By Googol in forum New To JavaReplies: 3Last Post: 10-30-2012, 04:06 PM -
Reading strings with like "degree symbol" - HOW?
By RR_QQ in forum New To JavaReplies: 13Last Post: 02-18-2009, 03:16 AM -
the dollar sign "$", prints like any other normal char in java like "a" or "*" ?
By lse123 in forum New To JavaReplies: 1Last Post: 10-20-2008, 08:35 AM
Bookmarks