How can I read input from the console using the Scanner class in Java?

前端 未结 15 1984
我寻月下人不归
我寻月下人不归 2020-11-21 06:19

How could I read input from the console using the Scanner class? Something like this:

System.out.println(\"Enter your username: \");
Scanner = i         


        
15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 06:51

    When the user enters his/her username, check for valid entry also.

    java.util.Scanner input = new java.util.Scanner(System.in);
    String userName;
    final int validLength = 6; // This is the valid length of an user name
    
    System.out.print("Please enter the username: ");
    userName = input.nextLine();
    
    while(userName.length() < validLength) {
    
        // If the user enters less than validLength characters
        // ask for entering again
        System.out.println(
            "\nUsername needs to be " + validLength + " character long");
    
        System.out.print("\nPlease enter the username again: ");
        userName = input.nextLine();
    }
    
    System.out.println("Username is: " + userName);
    

提交回复
热议问题