gpt4 book ai didi

java - 计算器控制台应用程序无法运行

转载 作者:行者123 更新时间:2023-12-02 03:15:53 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的计算器控制台应用程序。无论我做什么,答案都是 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;
}
}

最佳答案

正如其他人已经说过的,需要在输出之前完成计算。

我建议一些更多的改进:

  1. 使用正确的变量命名。例如,addition 是一个运算,但变量保存此运算的结果,通常称为 sum。因此,请使用这些名称作为您的变量。实际上,您不需要四个不同的变量,请参见下文。

  2. 在需要的地方声明变量,而不是在函数的开头。

  3. 在您的代码中,始终执行四种可能的计算,而不仅仅是用户选择的计算。

代码的第二部分(输入之后)可能如下所示:

    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);

关于java - 计算器控制台应用程序无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com