Die Frage ist am Ende, da es um die Konsolenausgabe geht.
Code: Select all
public class DeletePreviousInputs {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws InterruptedException, IOException {
System.out.println("write something in the console");
/*
* What I wrote:
1 2 3 4
*/
Thread.currentThread();
Thread.sleep(8000); //simulates delay
deleteInput();
System.out.println("after input should be deleted");
System.out.println(scanner.nextLine());
System.out.println(scanner.nextLine());
System.out.println(scanner.nextLine());
}
//Version 1 of the deleteInput()-Method:
private static void deleteInput() throws InterruptedException {
try {
while (System.in.available() > 0) {
//This is the part, where the code will differ in Version 2
scanner.nextLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Version 2 of the deleteInput()-Method:
private static void deleteInput() throws InterruptedException {
try {
while (System.in.available() > 0) {
//This is the part, where the code differs
Scanner dummyScanner = new Scanner(System.in);
dummyScanner.nextLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Code: Select all
write something in the console
1
2
3
after input should be deleted
2
3
write something in the console
1
2
3
after input should be deleted
< /code>
Warum funktioniert Version 1 nicht alle vorherigen Eingaben?
Warum funktioniert Version 2 perfekt? funktioniert und der andere funktioniert nicht.