【发布时间】:2016-05-14 06:12:03
【问题描述】:
我是 Java 的新手编码器,我正在尝试在 Java 中制作这个计算器,用户可以在其中输入两个数字并选择要对这些数字执行的操作。但是,当代码选择运算符时,它会跳过用户输入和 if 语句,直接实现 else 语句。
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}
【问题讨论】:
-
除了你的编程问题:你可能想检查除以零;)
-
为了解释与重复主题的链接,nextInt() 不消耗“新行”表达式,所以添加一个 nextLine() 第二个 nextInt() 之后的指令。
标签: java java.util.scanner calculator calc