我正在尝试制作一个简单的计算器控制台应用。无论我做什么,答案都会保持为0。如果没有给我直接答案,任何人都可以告诉我有什么问题。
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int firstNum;
int secondNum;
int division = 0, addition = 0, subtraction = 0, multiplication = 0;
String userChoice = "";
String choices[] = {"add","multiply","divide","subtract"};
System.out.print("Please enter first number: ");
firstNum = input.nextInt();
System.out.print("Please enter second number: ");
secondNum = input.nextInt();
System.out.println("What type of operation would you like to perform?");
System.out.println("add, multiply, subtract or divide.");
input.nextLine();
userChoice = input.nextLine();
if (userChoice.equals("add"))
System.out.print("The answer is " + addition);
else if (userChoice.equals("multiply"))
System.out.print("The answer is " + multiplication);
else if (userChoice.equals("subtract"))
System.out.print("The answer is " + subtraction);
else if (userChoice.equals("divide"))
System.out.print("The answer is " + division);
division = firstNum / secondNum;
addition = firstNum + secondNum;
subtraction = firstNum - secondNum;
multiplication = firstNum * secondNum;
}
}
答案 0 :(得分:2)
正如其他人已经说过的那样,计算需要在输出之前完成。
我建议进行一些改进:
使用适当的变量命名。例如,addition
是一个操作,但变量保存此操作的结果,通常称为sum
。因此,请将这些名称用于变量。实际上,您不需要四个不同的变量,见下文。
在您需要的地方声明您的变量,而不是在函数的开头。
在您的代码中,始终执行四种可能的计算,而不仅仅是用户选择的计算。
代码的第二部分(在输入之后)可能如下所示:
int result = 0;
if (userChoice.equals("add")) {
result = firstNum + secondNum;
}
else if (userChoice.equals("subtract")) {
result = firstNum - secondNum;
}
else if (userChoice.equals("multiply")) {
result = firstNum * secondNum;
}
else if (userChoice.equals("divide")) {
// maybe check if secondNum is not zero
result = firstNum / secondNum;
}
else {
System.out.print("Invalid input " + userChoice);
return;
}
System.out.print("The answer is " + result);