Issue
I'm trying to terminate this Scanner while loop when there is no more input for it to read. The input is two numbers per line separated by a space. The next line contains the same, and so on, for an undisclosed amount of lines. The output should then be the difference of those two numbers.
The input could for example be
10 12
71293781758123 72784
1 12345677654321
Where the output would then be
2
71293781685339
12345677654320
The code works when simply figuring out the difference, but I am unable to find a way to end the while loop.
If i attempt to set the condition to while (!sc.next().equals(""))
it reads the whitespace between every two number as the condition, and skips the second number.
I am not able to create a manual break by doing something like if (sc.next().equals("exit")
as the output has to be only the difference and nothing else.
public static void main(String[] args) {
long output;
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
long nr1 = sc.nextLong();
long nr2 = sc.nextLong();
if (nr1 > nr2) {
output = nr1 - nr2;
} else {
output = nr2 - nr1;
}
System.out.println(output);
}
}
Again, I'm looking for a way to terminate it when there are no more lines with two numbers on it. I've been googling like crazy for this issue, but have not been able to find a solution that fixed my issue. Any and all help is very appreciated!
Solution
If you want to terminate the loop when you get ""
as input, then just have an input
variable in your code.
String input;
while(sc.hasNextLine() && !(input = sc.nextLine()).equals("")) {
//Now you have your input and you need to parse it.
//There are many ways to parse a string.
String[] numbers = input.split(" ");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println( num1 > num2 ? num1 - num2 : num2 - num1);
}
Answered By - Aditya Arora
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)