Home > OS >  Reading numbers from file using Scanner
Reading numbers from file using Scanner

Time:01-19

This is my simple program which counts the sum of the numbers in the file

int sum = 0;

        try(Scanner s = new Scanner(new File(path)))
        {
            while (s.hasNextInt())
            {
                if (s.hasNextInt())
                {
                    sum  = s.nextInt();
                }
                else
                {
                    s.next();
                }
            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

        System.out.println(sum);

Why it doesnt work if i do something like that:

Scanner s = new Scanner(path)

instead of

Scanner s = new Scanner(new File(path))

CodePudding user response:

Your while loop loops only if s.hasNextInt() is true (because you wrote while (s.hasNextInt()). You then again check: if (s.hasNextInt().

This if is useless. Of course s.hasNextInt() is true. If it wasn't, the while loop wouldn't have looped!

It sounds like you want to do two things:

  1. make that while (s.hasNext()) instead.
  2. Fix your deplorable exception handling. Ditch the catch. Add throws IOException to the method (and to main if you want, psv main() can, and usually should, be declared as public static void main(String[] args) throws Exception. Less code, and errors with way more detail. Win-win.
  •  Tags:  
  • java
  • Related