我对编程比较陌生,最近开始学习Java以进入Android编程。我认为我会创建一个非常简单的计算器来练习,但似乎我的if语句不起作用。Java计算器不执行if语句
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Create new scanner object
Scanner numInput = new Scanner(System.in);
//Enter first number
System.out.println("Please enter the first number: ");
int num1 = numInput.nextInt();
//Enter the second number
System.out.println("Please enter the second number: ");
int num2 = numInput.nextInt();
//Choose the operation to perform (+,-,*,/)
System.out.println("What operation would you like to do?");
System.out.println("Type \"+\" to add.");
System.out.println("Type \"-\" to subtract.");
System.out.println("Type \"*\" to multiply.");
System.out.println("Type \"/\" to divide.");
String opChoice = numInput.nextLine();
//Add
if (opChoice.equals("+")) {
int ans = num1 + num2;
System.out.println("Adding " + num2 + " to " + num1 + " equals " + ans + ".");
}
//Subtract
else if (opChoice.equals("-")) {
int ans = num1 - num2;
System.out.println("Subtracting " + num2 + " from " + num1 + " equals " + ans + ".");
}
//Multiply
else if (opChoice.equals("*")) {
int ans = num1 + num2;
System.out.println("Multiplying " + num2 + " with " + num1 + " equals " + ans + ".");
}
//Divide
else if (opChoice.equals("/")) {
int ans = num1 + num2;
System.out.println("Dividing " + num1 + " by " + num2 + " equals " + ans + ".");
}
}
}
我正在使用Eclipse IDE,它运行良好,直到它询问要执行哪个操作。它会显示选项,但不会让我输入任何东西(我已经用5乘以2来测试它)。
我搜索了类似的问题,并尝试了他们的建议,但它似乎仍然不起作用。我很感激任何帮助,我认为这可能只是一些简单的错误,所以我很抱歉,如果这看起来像一个愚蠢的问题!
编辑:感谢您的快速反应,伙计们!我很感激。是的,我固定了乘法和除法。 :)
,我还没有碰到但有趣的问题。你每天学习新的东西! – csmckelvey