我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
当前回答
下面是使用java.util.Scanner的问题中的程序:
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
int input = 0;
System.out.println("The super insano calculator");
System.out.println("enter the corrosponding number:");
Scanner reader3 = new Scanner(System.in);
System.out.println(
"1. Add | 2. Subtract | 3. Divide | 4. Multiply");
input = reader3.nextInt();
int a = 0, b = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
// get user input for a
a = reader.nextInt();
Scanner reader1 = new Scanner(System.in);
System.out.println("Enter the scend number");
// get user input for b
b = reader1.nextInt();
switch (input){
case 1: System.out.println(a + " + " + b + " = " + add(a, b));
break;
case 2: System.out.println(a + " - " + b + " = " + subtract(a, b));
break;
case 3: System.out.println(a + " / " + b + " = " + divide(a, b));
break;
case 4: System.out.println(a + " * " + b + " = " + multiply(a, b));
break;
default: System.out.println("your input is invalid!");
break;
}
}
static int add(int lhs, int rhs) { return lhs + rhs; }
static int subtract(int lhs, int rhs) { return lhs - rhs; }
static int divide(int lhs, int rhs) { return lhs / rhs; }
static int multiply(int lhs, int rhs) { return lhs * rhs; }
}
其他回答
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
使用JOptionPane就可以实现。
Int a =JOptionPane.showInputDialog(null,"Enter number:");
你可以像这样使用BufferedReader获取用户输入:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
这就是应用它们的方法
String name = br.readline();
因此,当用户在控制台中输入他的名字时,“字符串名称”将存储该信息。
如果它是一个你想要存储的数字,代码将像这样:
int x = Integer.parseInt(br.readLine());
希望这能有所帮助!
下面是获取键盘输入的方法:
Scanner scanner = new Scanner (System.in);
System.out.print("Enter your name");
String name = scanner.next(); // Get what the user types.
然后,Add在main()旁边抛出IOException
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();