Java - Löschen früherer Konsoleneingänge aus System.in - Warum funktioniert 1 Version meines Codes und nicht die andere Java

Java-Forum
Anonymous
 Java - Löschen früherer Konsoleneingänge aus System.in - Warum funktioniert 1 Version meines Codes und nicht die andere

Post by Anonymous »

Die Differenz im Code liegt in der Methode Löschen input ()-. Alles andere ist gleich.
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();
}
}
}
Ausgabeversion 1:

Code: Select all

write something in the console
1
2
3
after input should be deleted
2
3
Ausgabeversion 2:
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.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post