Results 1 to 6 of 6
  1. #1
    Zelaine is offline Senior Member
    Join Date
    Aug 2013
    Location
    Sweden
    Posts
    163
    Rep Power
    7

    Question "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.
    FYI, the numbers are the grades.
    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){
    		}
    	}
    }

  2. #2
    Kramko is offline Member
    Join Date
    Oct 2013
    Posts
    4
    Rep Power
    0

    Default 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){
            }
        }
    }
    The change above should get your program running, but there are some other things you may want to consider:

    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();
    	}
    }
    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. If you need to use the data at some other point in the program you'll need to use arrays or some sort of Collection to keep track of that data.

    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!

  3. #3
    Zelaine is offline Senior Member
    Join Date
    Aug 2013
    Location
    Sweden
    Posts
    163
    Rep Power
    7

    Default 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.
    It was an assignment in a book which told me that I had to use two-dimensional arrays, so that was why I used them. Same thing goes with that the maximum amount of students is 30.

    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.

  4. #4
    Zelaine is offline Senior Member
    Join Date
    Aug 2013
    Location
    Sweden
    Posts
    163
    Rep Power
    7

    Default 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.

  5. #5
    Zelaine is offline Senior Member
    Join Date
    Aug 2013
    Location
    Sweden
    Posts
    163
    Rep Power
    7

    Default 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();
    	}
    }

  6. #6
    Kramko is offline Member
    Join Date
    Oct 2013
    Posts
    4
    Rep Power
    0

    Default Re: "Complex" File Reading

    Hi sorry for the confusion,

    it should be:
    Java Code:
    String.format("%.2f",averageScore);
    The exception throwing line was my way of handling the Scanner trying to read a Line that didn't exist. You can remove that line as it doesn't make a ton of sense in a main method, unless you do catch it -- but when you start breaking your program into smaller pieces, throwing errors when something goes wrong is pretty standard, you then allow that error to be handled where the method is called.

    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

  1. Reading from a File, ArrayList and "reference"
    By pokadean in forum New To Java
    Replies: 5
    Last Post: 09-12-2013, 10:03 PM
  2. Replies: 0
    Last Post: 12-07-2012, 09:29 AM
  3. Replies: 3
    Last Post: 10-30-2012, 04:06 PM
  4. Reading strings with like "degree symbol" - HOW?
    By RR_QQ in forum New To Java
    Replies: 13
    Last Post: 02-18-2009, 03:16 AM
  5. Replies: 1
    Last Post: 10-20-2008, 08:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •