Page 1 of 3 123 LastLast
Results 1 to 20 of 50
  1. #1
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Reading From File Question??

    My code is below (it works)...however, I am wondering how to put this in a try/catch? For instance, if the file cannot be found, or problems with reading data throw exception. Also I'm kind of new to Java and I can't figure out how to ask the user for the filename and then use Scanner to read from that file...

    Java Code:
    public class ProcessScores {
    	
    	public static void main (String args[]) throws FileNotFoundException	{
    		Scanner inFile = new Scanner(new FileReader ("scores.txt"));
            int counter = 0; // Keep track of how many integers are in the file
            double sum = 0; 
            
            while(inFile.hasNextInt())	{
                counter++;
                inFile.nextInt();
            }
            Scanner inFile2 = new Scanner(new FileReader ("scores.txt"));
            int scoresArray[] = new int[counter];
            for(int i=0;i<counter;i++)	{
                scoresArray[i]=inFile2.nextInt(); //fill the array with the integers
                sum += scoresArray[i];
            }
            
            Arrays.sort(scoresArray);
            
            letterGrades(scoresArray, counter);
            average(sum, counter);
    
    	}
    	
    	public static void average (double sum, int counter)	{
    		DecimalFormat format = new DecimalFormat();
            format.setMaximumFractionDigits(2);
            System.out.println("\nThe average test score is: " + format.format(sum/counter));
    	}
    	
    	public static void letterGrades(int[] scores, int counter){
    		System.out.println("Score\tLetter Grade");
    		System.out.println("------------------------------");
    		
    		for(int i=0;i<counter;i++)	{
    			if (scores[i] <= 100 && scores[i] > 89)
    				System.out.println(scores[i] +"\t\tA");
    			else if (scores[i] <= 89 && scores[i] > 79)
    			System.out.println(scores[i] +"\t\tB");
    			else if (scores[i] <= 79 && scores[i] > 69)
    				System.out.println(scores[i] +"\t\tC");
    			else if (scores[i] <= 69 && scores[i] > 59)
    				System.out.println(scores[i] +"\t\tD");
    			else if (scores[i] <= 59 && scores[i] >= 0)
    				System.out.println(scores[i] +"\t\tF");
    		}
    		System.out.println("------------------------------");
    	}
    }
    Here's sample file:
    Java Code:
    79  86  97  82  90  89
    68 72 87 78 
    95 
    99
    Also how would I go about it if the file didn't have just ints? Like...
    Java Code:
    79  86  97  82  Bob 90  89
    68 72 87 78 ffff 95 
    99 dodo

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    how to put this in a try/catch?
    A try{}catch is sort of like an if else with the code inside of the try{} being the condition for the if.
    If there are no exceptions thrown the catch block is not executed. If there is an exception it is thrown:
    if(this code executes with no exception) {
    // continue below
    }else { // if there is an exception
    // do the code in the catch block here
    }
    The two paths through the above if statement will both continue here

    You put the try{} around the code that can have an exception.

    What do you want the code to do when there is an exception? Skip the number or exit the program or ???

  3. #3
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    I would want it to skip and go on to the next. Also how would it go if I were going to ask the user what the name of the file is? I would want to make sure they enter in a filename that is available??

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    make sure they enter in a filename that is available?
    See the File class. It can test if a file exists.

  5. #5
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    Do you know of a good example somewhere that shows how to grab the input from the user in order to read that file??

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    You could use the Scanner class to get input from a user. There are lots of code examples on this forum.

  7. #7
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    Quote Originally Posted by Norm View Post
    What do you want the code to do when there is an exception? Skip the number or exit the program or ???
    Let's say the user input a correct file...the file has letters in it, but I only want the numbers. How do I continue to scan the file even after string/char is found? For instance...

    Java Code:
    79  86  97  82  90  89
    68 72 87 78 95 99 
    100 10 ff
    12 13

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    How do I continue to scan the file even after string/char is found?
    It depends on what class and methods you are using to read the file.
    If you read an invalid token/word from the file, ignore it and go back and read the next token/word.
    pseudo code:
    begin loop
    read token
    if token is invalid continue back to the top of the loop to read the next token
    process the token
    end of loop

  9. #9
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    I am using
    Java Code:
      Scanner inFile2 = new Scanner(new FileReader (fName));
    	        int scoresArray[] = new int[counter];
    	        for(int i=0;i<counter;i++)	{
    	            scoresArray[i]=inFile2.nextInt(); // Fill the array with the integers
    	            sum += scoresArray[i];
    	        }
    How would you loop to read the next token without adding it to the array? Right now if the file has anything other than an int it completely stops reading the file and exits displaying what it did read..up until the invalid token.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    How would you loop to read the next token without adding it to the array?
    By doing it in several steps:
    read the next token into a temp variable
    validate it
    add it to array

    To keep control of the file input method calls, you need to put them in a try{}catch block.

  11. #11
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    What else would I need to do for lines 13-16??

    Java Code:
    try	{
    			Scanner inFile = new Scanner(new FileReader (fName));
    	        
    	        while(inFile.hasNextInt())	{
    	            counter++;
    	            inFile.nextInt();
    	        }
    	        
    	        Scanner inFile2 = new Scanner(new FileReader (fName));
    	        int scoresArray[] = new int[counter];
    	        for(int i=0;i<counter;i++)	{
    	        	
    	        	if(inFile2.next() != int){ // What do I need to put for int??
    	        		Exception problem = new Exception("Value is not an int");
    	        		throw problem;
    	        		... // How do you make it continue through the file after exception?
    	        	}
    	            scoresArray[i]=inFile2.nextInt(); // Fill the array with the integers
    	            sum += scoresArray[i];
    	        }
            
    	        Arrays.sort(scoresArray);
    	        letterGrades(scoresArray, counter);
    	        average(sum, counter);
    		}
    		catch (FileNotFoundException e)	{
    			System.out.println(fName + ": could not be found.");
    		}

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    What else would I need to do for lines 13-16??
    What are you trying to do on those lines?
    If you want to test if a String is a valid integer, use the Integer parse int method. It will throw an exception if the String does not contain a valid number.

  13. #13
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    Ok I did the following...and when it gets to anything not an int it stops. However, I want it to skip that token and continue to the next.

    Java Code:
     Scanner inFile2 = new Scanner(new FileReader (fName));
    	        int scoresArray[] = new int[counter];
    	        String tempArray[] = new String[counter];
    	        for(int i=0;i<counter;i++)	{
    	        	
    	            tempArray[i]=inFile2.next(); // Fill the array
    	            scoresArray[i] = Integer.parseInt(tempArray[i]);
    	            sum += scoresArray[i];
    	        }

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    Back in post #10 I suggested the steps to take.
    1) read the token into a temp variable not an array.

    You need to put the parseInt call inside of a try{} catch block. If the number is invalid, parseInt throws an exception.

  15. #15
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    Ok this is what I did... temp is a string now

    Java Code:
    try	{
    			Scanner inFile = new Scanner(new FileReader (fName));
    	        
    	        while(inFile.hasNext())	{
    	            counter++;
    	            inFile.next();
    	        }
    	        
    	        Scanner inFile2 = new Scanner(new FileReader (fName));
    	        int scoresArray[] = new int[counter];
    	        for(int i=0;i<counter;i++)	{
    	        	
    	            temp=inFile2.next(); // Fill the array with the integers
    
    	            scoresArray[i] = Integer.parseInt(temp);
    	            sum += scoresArray[i];
    	            //System.out.println(temp);
    	        }
            
    	        Arrays.sort(scoresArray);
    	        letterGrades(scoresArray, counter);
    	        average(sum, counter);
    		}
    		catch (FileNotFoundException e)	{
    			System.out.println(fName + ": could not be found.");
    		}
    		catch(NumberFormatException e) {
    		    System.out.println("Not an Integer");
    		}
    Now when the file has letters I get the Exception "Not an Integer". If the files has anything that is not an integer I just want to skip it and move on until the end of the file. I'm not sure how to validate that??

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,446
    Rep Power
    25

    Default Re: Reading From File Question??

    I get the Exception
    Yes that is what you expect when nextInt reads bad data. You need to put the call to parseInt() inside of a try catch block.
    Use the continue statement to go back to the next() call
    See post#2 again.

    how to validate that??
    The thrown exception says the value read was invalid.

  17. #17
    diamonddragon is offline Senior Member
    Join Date
    Jan 2012
    Posts
    210
    Rep Power
    3

    Default Re: Reading From File Question??

    Quote Originally Posted by Norm View Post
    What are you trying to do on those lines?
    If you want to test if a String is a valid integer, use the Integer parse int method. It will throw an exception if the String does not contain a valid number.
    Or maybe something like this:

    Java Code:
    String temp = input.next();
    if (temp.matches("[\\d]*"))
       (something with temp)

  18. #18
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    What does the temp.matches("[\\d]*") do??

  19. #19
    diamonddragon is offline Senior Member
    Join Date
    Jan 2012
    Posts
    210
    Rep Power
    3

    Default Re: Reading From File Question??

    Quote Originally Posted by kraigballa View Post
    What does the temp.matches("[\\d]*") do??
    Validate if temp(next complete token) is only od digits.

  20. #20
    kraigballa is offline Senior Member
    Join Date
    Oct 2011
    Posts
    115
    Rep Power
    0

    Default Re: Reading From File Question??

    I tried that and now I get

    Java Code:
      if(temp.matches("[\\d]*")){
    	            	scoresArray[i] = Integer.parseInt(temp);
    	            }else{
    	            	temp = inFile2.next();
    	            }
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:838)
    at java.util.Scanner.next(Scanner.java:1347)
    at ProcessScores.main(ProcessScores.java:35)
    Last edited by kraigballa; 01-25-2012 at 03:53 AM.

Page 1 of 3 123 LastLast

Similar Threads

  1. Question about fast reading files in Java.
    By Martino in forum Suggestions & Feedback
    Replies: 0
    Last Post: 05-09-2011, 03:34 PM
  2. URL Reading question
    By g123456 in forum New To Java
    Replies: 5
    Last Post: 03-17-2010, 03:07 AM
  3. Replies: 11
    Last Post: 11-03-2009, 05:32 PM
  4. [SOLVED] File reading question
    By wiz0r in forum New To Java
    Replies: 5
    Last Post: 04-19-2009, 01:21 AM
  5. Question abt.reading xml file using java
    By gvi in forum Advanced Java
    Replies: 6
    Last Post: 11-08-2007, 05:48 PM

Posting Permissions

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