gpt4 book ai didi

java - Java 中的基本计算器

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:21 24 4
gpt4 key购买 nike

我正在尝试用 Java 创建一个基本的计算器。我对编程很陌生,所以我正在努力适应它。

import java.util.Scanner;
import javax.swing.JOptionPane;

public class javaCalculator
{

public static void main(String[] args)
{
int num1;
int num2;
String operation;


Scanner input = new Scanner(System.in);

System.out.println("please enter the first number");
num1 = input.nextInt();

System.out.println("please enter the second number");
num2 = input.nextInt();

Scanner op = new Scanner(System.in);

System.out.println("Please enter operation");
operation = op.next();

if (operation == "+");
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation == "-");
{
System.out.println("your answer is" + (num1 - num2));
}

if (operation == "/");
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation == "*")
{
System.out.println("your answer is" + (num1 * num2));
}


}
}

这是我的代码。它提示输入数字和操作,但同时显示答案?

最佳答案

if 语句中删除分号,否则后面的代码将独立并始终执行:

if (operation == "+");
^

同样对Strings使用.equals==比较Object引用:

 if (operation.equals("+")) {

关于java - Java 中的基本计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675815/

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