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

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

    Here is the complete class which performs the required operation:

    import java.util.Scanner;
    
    public class App {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            final int valid = 6;
    
            Scanner one = new Scanner(System.in);
            System.out.println("Enter your username: ");
            String s = one.nextLine();
    
            if (s.length() < valid) {
                System.out.println("Enter a valid username");
                System.out.println(
                    "User name must contain " + valid + " characters");
                System.out.println("Enter again: ");
                s = one.nextLine();
            }
    
            System.out.println("Username accepted: " + s);
    
            Scanner two = new Scanner(System.in);
            System.out.println("Enter your age: ");
            int a = two.nextInt();
            System.out.println("Age accepted: " + a);
    
            Scanner three = new Scanner(System.in);
            System.out.println("Enter your sex: ");
            String sex = three.nextLine();
            System.out.println("Sex accepted: " + sex);
        }
    }
    

提交回复
热议问题