Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading numbers from file using Scanner

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

instead of

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

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading