我是java的新手。我正在用Herbert Schildt的书学习Java。我想编写要求用户输入两个变量的程序,然后要求选择算术运算然后程序执行此操作(就像任何计算器一样)。我使用这种方法 - 来自Schildts book的System.in.read
,但我的程序只能要求用户输入一个变量。程序不会要求用户输入第二个变量。我怎么能这样做?
我的代码如下:
class Calc {
public static void main(String args[])
throws java.io.IOException {
int a, b, result;
System.out.print("Enter first digit ");
a = (int) System.in.read();
System.out.println("Enter second digit ");
b = (int) System.in.read();
System.out.println("Choose operation");
System.out.println("Multiplication - 1 or Division - 2 ");
//int r;
result = (int) System.in.read();
switch(result) {
case 1:
System.out.println(a * b);
break;
case 2:
System.out.println(a / b);
break;
default: System.out.println("incorrect digit");
}
}
}
答案 0 :(得分:-1)
public static void main(String args[]) {
int a, b, result;
final Scanner sc = new Scanner(System.in);
System.out.print("Enter first digit ");
a = sc.nextInt();
System.out.println("Enter second digit ");
b = sc.nextInt();
System.out.println("Choose operation");
System.out.println("Multiplication - 1 or Division - 2 ");
// int r;
result = sc.nextInt();
switch (result) {
case 1:
System.out.println(a * b);
break;
case 2:
System.out.println(a / b);
break;
default:
System.out.println("incorrect digit");
}
}