【发布时间】:2014-02-06 07:19:53
【问题描述】:
我对编程比较陌生,最近开始学习 Java,以便进入 Android 编程领域。我以为我会创建一个非常简单的计算器来练习,但是我的 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 对其进行测试)。
我搜索了类似的问题并尝试了他们的建议,但它似乎仍然不起作用。我会很感激任何帮助,我认为这可能只是我犯的一些简单错误,所以如果这看起来是一个愚蠢的问题,我深表歉意!
编辑:感谢您的快速回复,伙计们!我很感激。是的,我修复了乘法和除法。 :)
【问题讨论】:
-
我还没有遇到的有趣问题。你每天都能学到新东西!
标签: java if-statement calculator