Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Nov 2008
    Location
    Melbourne, Australia
    Posts
    69
    Thanks
    8
    Thanked 1 Time in 1 Post

    reading a text file and saving integers into variables

    hey, im new to java.... i have got the text file, i can read it but i cant seem to figure out how to get all the values(integers) from the text file and save them in variables. I have got the fisrt one to work and i cant get the rest to work... im running out of ideas

    here is the code
    Code:
    public  FivePointLikertAnalyser(String fileName) throws FileNotFoundException {
             inFile = new Scanner(new FileReader(fileName));//text file from main class
             while (inFile.hasNext()){
                 addScores();
                 }
           inFile.close();
           }
           
    //text file results
    public void addScores() {
          
              val = inFile.nextInt();
              if(inFile.hasNextInt()){
              
                  if (val == 10000){
                     val5++;
                     count++;}
                
                 if (val == 1000){
                     val4++;
                     count++;}
              }
    the first couple of numbers in my text file
    01000
    10000
    00001

    any help would be great
    Last edited by kryssy23; 09-11-2009 at 05:01 AM. Reason: fixed part of the problem

  • #2
    Senior Coder TheShaner's Avatar
    Join Date
    Sep 2005
    Location
    Orlando, FL
    Posts
    1,126
    Thanks
    2
    Thanked 40 Times in 40 Posts
    In your code, you do a val = inFile.nextInt();. This grabs the first integer of the line of text you're reading. However, your next line of code, you do if(inFile.hasNextInt()); since there is only one integer per line and you've already read in the only integer on that line, that if statement never gets executed.

    As for coding style, it looks like all your variables are declared globally elsewhere in your code and the variable names are not very descriptive, which is not good practice. For example, your variable val is only being used inside of addScores() for retrieving the integer from the text file, so it should be declared inside that function:
    Code:
    int val = inFile.nextInt();
    -Shane


  •  

    Posting Permissions

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