How to Terminate Scanner When Input Is Complete

How to terminate Scanner when input is complete?

The problem is that a program (like yours) does not know that the user has completed entering inputs unless the user ... somehow ... tells it so.

There are two ways that the user could do this:

  • Enter an "end of file" marker. On UNIX and Mac OS that is (typically) CTRL+D, and on Windows CTRL+Z. That will result in hasNextLine() returning false.

  • Enter some special input that is recognized by the program as meaning "I'm done". For instance, it could be an empty line, or some special value like "exit". The program needs to test for this specifically.

(You could also conceivably use a timer, and assume that the user has finished if they don't enter any input for N seconds, or N minutes. But that is not a user-friendly way, and in many cases it would be dangerous.)


The reason your current version is failing is that you are using == to test for an empty String. You should use either the equals or isEmpty methods. (See How do I compare strings in Java?)

Other things to consider are case sensitivity (e.g. "exit" versus "Exit") and the effects of leading or trailing whitespace (e.g. " exit" versus "exit").

How to terminate a Scanner while loop that takes input seperated by both whitespace and linebreaks

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);
}

Java Scanner input validation causing loop to end early

        double currentNum = 0.0;
while (index < arraySize) {
System.out.print("Time for lap or length #" + (index + 1) + ": ");
currentNum = sc.nextDouble();
if (currentNum > 0 && currentNum < 61) {
lapArray[index] = currentNum;
index++;
} else if (currentNum < 0 || currentNum > 60) {
System.out.println("Invalid input! Time must be between 0 and 60.");
}
}

Since you're running for-loop, i is getting incremented every time (even if your validation fails).

How to finish program with Scanner.hasNext in Java

The Scanner will continue to read until it finds an "end of file" condition.

As you're reading from stdin, that'll either be when you send an EOF character (usually ^d on Unix), or at the end of the file if you use < style redirection.

However, to put the input from the user in your array, can be done by replacing your while condition with this:

while (sc.hasNext() && i!=arr.length) {
arr[i++] = sc.nextInt();

}

Scanner input - end of input stream indicator

Also you can use a sentinel input to terminate the loop i.e an input not used in the computation. e.g

while ( (inscan.hasNext()) ){
String val = inscan.next();
if(val.equals("!"))
break;
stk.push(Integer.parseInt(val));
}

Update: loop terminates on entering '!'

How to stop Java Scanner from accepting input

A Java Scanner is using blocking operations. It is not possible to stop it. Not even using Thread.interrupt();

You can however read using a BufferedLineReader and be able to stop the thread. It's not a neat solution, as it involves pausing for short moments (otherwise it would use 100 % CPU), but it does work.

public static class ConsoleInputReadTask {
private final AtomicBoolean stop = new AtomicBoolean();

public void stop() {
stop.set(true);
}

public String requestInput() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("ConsoleInputReadTask run() called.");
String input;
do {
System.out.println("Please type something: ");
try {
// wait until we have data to complete a readLine()
while (!br.ready() && !stop.get()) {
Thread.sleep(200);
}
input = br.readLine();
} catch (InterruptedException e) {
System.out.println("ConsoleInputReadTask() cancelled");
return null;
}
} while ("".equals(input));
System.out.println("Thank You for providing input!");
return input;
}
}

public static void main(String[] args) {
final Thread scannerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String string = new ConsoleInputReadTask().requestInput();
System.out.println("Input: " + string);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
});
scannerThread.start();

new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
scannerThread.interrupt();
}
}).start();
}

Terminating a user input determined Scanner?

if you want the program to take only X amount of numbers, you could have a counter and break the while loop after it has executed X number of times. Alternatively, you could also use a for loop to make things easier.

You could also use Ctrl+Z in eclipse to stop console from waiting for inputs.



Related Topics



Leave a reply



Submit