Reputation: 69
I have a problem with last line of input. I cannot force Scanner to read a number from last line since it is unfinished. When I copy input with one more line after the previous last line, there is no problem, but i cannot have the extra line there.
Example of input:
2
1 1
9 9
4
4 5
6 5
2 5
3 4
-1
I've tried sc.nextInt()
, sc.next()
, sc.nextLine()
and nothing can reach the -1
. Even sc.hasNext
, sc.hasNextInt
etc. are waiting.
while(true)
{
line = sc.nextLine();
try {
a = Integer.parseInt(line);
}
catch (NumberFormatException e) {
}
if(a == -1)
{
break;
}
rr = new int[a][2];
for(int i = 0; i < a; i++)
{
line = sc.nextLine();
numbers = line.split(" ");
try {
rr[i][0] = Integer.parseInt(numbers[0]);
rr[i][1] = Integer.parseInt(numbers[1]);
}
catch (NumberFormatException e) {
}
}
b = sc.nextInt();
sc.nextLine();
tt = new int[b][2];
for(int i = 0; i < b; i++)
{
line = sc.nextLine();
numbers = line.split(" ");
try {
tt[i][0] = Integer.parseInt(numbers[0]);
tt[i][1] = Integer.parseInt(numbers[1]);
}
catch (NumberFormatException e) {
}
}
sc.nextLine();
}
Upvotes: 0
Views: 146
Reputation: 3021
while(true) {
// read the line..
line = sc.nextLine().trim();
// check if it's a blank line...
// blank line means new test case.. Take the value of n
if (line.length() == 0) line = sc.nextLine().trim();
// now parse the value of n.. If it's -1 then end of input
a = Integer.parseInt(line);
if (a==-1) break;
// rest of your input
}
Take the value of b
like this:
b = Integer.parseInt(sc.nextLine().trim());
And remove the 'extra' sc.nextLine()
from below of b
and from the bottom of while loop. That case is handled at the top.
Upvotes: 1
Reputation: 82
Before trying to get the -1 you could have a separate scanner use the delimiter /n (line break) and have it delete the extra break between -1 and the last line before it. Then you could go through and just scan with .nextLine() or .nextInt().
Upvotes: 0