Home > Back-end >  I need to read only Integers from a random scanner text file in Java. I can't get it to skip no
I need to read only Integers from a random scanner text file in Java. I can't get it to skip no

Time:10-11

The problem is that I get a random text file and I have to have my code read it and get the average from the range (0-100) and no non integers can be counted. My issue is that after my while loops starts and goes to the if statement, my code checks the values in the text file and if it sees any non integers it completely stops. I have no idea how to fix this. I thought maybe in the if statement have something that tells the scanner to skip any strings but I am not sure how to do that. I tried doing the .skip() method and it lets my code run normal, but once you put characters (a-z and uppercase) it wont let the code run. Any ideas on what I can do to fix this? Input file examples: 23 23 44 55 100 0 39 58 thing

code:

           Scanner input = new Scanner(System.in);
           //asks for file's name
           System.out.print("Input File's name: " );
           String inputFile = input.nextLine();
           //reads the files data
           File file = new File(inputFile);
           Scanner scanFile = new Scanner(file);
           //finds average and totalCount

            while(scanFile.hasNext()) {
                String pattern = "[a-zA-Z]*";
                scanFile.skip(pattern);
                num = scanFile.nextInt();
                if(num >= 0 && num <= 100) {
                    sum  = num;
                    totalCount  ;   
                    average = sum/totalCount;
                    
                    if(num >= 90) {
                        gradeACount  ;
                        percentage = (gradeACount / (float)totalCount) * 100;
                        
                    }
                    
                    
                    if(num < minimumScore)
                        minimumScore = num;
                    
                    if(num > maximumScore)
                        maximumScore = num;
                    
                }
            }
            scanFile.close();

CodePudding user response:

There is no need to use skip() for this task. You can check if next token is integer or not and skip all not integers. For example:

while(scanFile.hasNext()) {
    if (!scanFile.hasNextInt()) {
         scanFile.next();
         continue;
    }

    System.out.println(scanFile.nextInt());
}

Output:

23 23 44 55 100 0 39 58

  • Related