How can I get the user input in Java?

2018-12-31 02:52发布

I attempted to create a calculator, but I can not get it to work because I don't know how to get user input.

How can I get the user input in Java?

24条回答
低头抚发
2楼-- · 2018-12-31 03:23

It is very simple to get input in java, all you have to do is:

import java.util.Scanner;

class GetInputFromUser
{
    public static void main(String args[])
    {
        int a;
        float b;
        String s;

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a string");
        s = in.nextLine();
        System.out.println("You entered string " + s);

        System.out.println("Enter an integer");
        a = in.nextInt();
        System.out.println("You entered integer " + a);

        System.out.println("Enter a float");
        b = in.nextFloat();
        System.out.println("You entered float " + b);
    }
}
查看更多
谁念西风独自凉
3楼-- · 2018-12-31 03:25

You can get user input using BufferedReader.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;  

System.out.println("Enter your Account number: ");
accStr = br.readLine();

It will store a String value in accStr so you have to parse it to an int using Integer.parseInt.

int accInt = Integer.parseInt(accStr);
查看更多
素衣白纱
4楼-- · 2018-12-31 03:26

Here, the program asks the user to enter a number. After that, the program prints the digits of the number and the sum of the digits.

import java.util.Scanner;

public class PrintNumber {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int num = 0;
        int sum = 0;

        System.out.println(
            "Please enter a number to show its digits");
        num = scan.nextInt();

        System.out.println(
            "Here are the digits and the sum of the digits");
        while (num > 0) {
            System.out.println("==>" + num % 10);
            sum += num % 10;
            num = num / 10;   
        }
        System.out.println("Sum is " + sum);            
    }
}
查看更多
怪性笑人.
5楼-- · 2018-12-31 03:27

Can be something like this...

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

    System.out.println("Enter a number: ");
    int i = reader.nextInt();
    for (int j = 0; j < i; j++)
        System.out.println("I love java");
}
查看更多
时光乱了年华
6楼-- · 2018-12-31 03:28

To read a line or a string, you can use a BufferedReader object combined with an InputStreamReader one as follows:

BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
查看更多
看淡一切
7楼-- · 2018-12-31 03:28
class ex1 {    
    public static void main(String args[]){
        int a, b, c;
        a = Integer.parseInt(args[0]);
        b = Integer.parseInt(args[1]);
        c = a + b;
        System.out.println("c = " + c);
    }
}
// Output  
javac ex1.java
java ex1 10 20 
c = 30
查看更多
登录 后发表回答