简体   繁体   中英

Why System.out.println "Input" comes out twice?

i'm new to programming and we've got an example from school to understand how Scanner works. My problem is that i do not understand why the message "Input" (System.out.println in the while loop) gets printed twice.

import java.util.Scanner;

class ScannerInput {
  public static void main(String[] args) {
    Scanner myScanner = new Scanner(System.in);

    System.out.println("Give me a String:");
    String zeichenkette = myScanner.nextLine();
    
    System.out.println("Give me an Integer:");
    int einInteger = myScanner.nextInt();

    // Output input by user
    System.out.println("String: " + zeichenkette);
    System.out.println("Integer: " + einInteger);
    
    boolean scannerSuccess = false;
    while(!scannerSuccess) {
        System.out.print("Input: ");
        if(myScanner.hasNextInt()) {
            einInteger=myScanner.nextInt();
            myScanner.nextLine();
            scannerSuccess=true;
        } else if(myScanner.hasNextLine()){
            myScanner.nextLine();
            scannerSuccess=false;
        }
    }
    
    
    myScanner.close();
  }
}
else if(myScanner.hasNextLine()){
  myScanner.next();
  scannerSuccess=false;
}

try this code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM