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:
- make that
while (s.hasNext())
instead. - Fix your deplorable exception handling. Ditch the catch. Add
throws IOException
to the method (and tomain
if you want,psv main()
can, and usually should, be declared aspublic static void main(String[] args) throws Exception
. Less code, and errors with way more detail. Win-win.