For the particular problem that you are trying to solve (HS08TEST), there is only one test case.
You don’t need any loops there. Just get rid of the while statement, and move everything out of its body.
For the general case, the input either contains the number of test cases at the top, followed by test case data, or it just contains test case data, and you are supposed to process until EOF.
For the second case, the format of input per test case would be well defined. For such cases you can check whether there are any more tokens available in the scanner, at the start of the loop. For example,
while (in.hasNext()) {
// do something. may be in.nextInt();
}
You can also use while (true)
, but that will lead to infinite loop. At some point, the program will try to read data that is not available, and will throw some runtime exception (which is what is happening in your case.) You can catch that exception using a try…catch… block, and use that to break out the while loop. But, I would say, that is a very very very very very bad practice. You should not be relying on exceptions to know when to break out of a loop. You should be using other available options.
Again, for the particular problem, you could use the general strategy. But, since the problem has only one test case, you can also get away with just writing the logic directly, and without any loops.
For problems that require you to iterate, i am sure, it would state somewhere that either there are multiple test cases and/or that you should read until EOF, and such.
And, of course, if the first line is the number of test cases, you don’t need to worry about this at all.
Happy programming!