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

前端 未结 15 2011
我寻月下人不归
我寻月下人不归 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 07:09

    A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in. It's really quite simple.

    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    

    To retrieve a username I would probably use sc.nextLine().

    System.out.println("Enter your username: ");
    Scanner scanner = new Scanner(System.in);
    String username = scanner.nextLine();
    System.out.println("Your username is " + username);
    

    You could also use next(String pattern) if you want more control over the input, or just validate the username variable.

    You'll find more information on their implementation in the API Documentation for java.util.Scanner

提交回复
热议问题