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

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

    You can make a simple program to ask for the user's name and print whatever the reply use inputs.

    Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.

    So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:

    Scanner input = new Scanner(System.in);
    

    input is a variable name.

    Scanner input = new Scanner(System.in);
    
    System.out.println("Please enter your name: ");
    s = input.next(); // Getting a String value
    
    System.out.println("Please enter your age: ");
    i = input.nextInt(); // Getting an integer
    
    System.out.println("Please enter your salary: ");
    d = input.nextDouble(); // Getting a double
    

    See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

    According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.

提交回复
热议问题