gpt4 book ai didi

java - 这段非常简单的代码有什么问题

转载 作者:行者123 更新时间:2023-12-01 07:54:54 25 4
gpt4 key购买 nike

当我运行我的代码时,它会正常工作,直到它询问“您想使用哪个操作( sum , subst , multi , div )”。无论用户选择什么,我的程序都没有任何响应!

为什么会发生这种情况?

import java.util.Scanner;
import java.io.*;

public class three3 {
public static void main (String[] args) {
int x;
int y;
int opera;
String oper;

Scanner in = new Scanner (System.in);
System.out.println(" write the first number ");
x = in.nextInt();

System.out.println(" write the second number ");
y = in.nextInt();

System.out.println(" which operation do you want to use from ( sum , subst , multi , div )");
oper = in.nextLine();

if (oper == "sum") {
opera=x+y;
System.out.println(" the sum of two numbers is " + opera );
}

if (oper == "subst") {
opera = x - y;
System.out.println(" the subtraction of two numbers is " + opera );
}

if (oper == "multi") {
opera = x * y;
System.out.println(" the multi of two numbers is " + opera );
}

if (oper == "div") {
opera = x / y;
System.out.println(" the division of two numbers is " + opera );
}
}
}

最佳答案

因为这些 if 子句都没有被执行。您将 Strings== 进行比较,这是错误的。请使用 oper.equals("sum") 来代替。请参阅this question以供引用。您的结论是始终对字符串使用equals

关于java - 这段非常简单的代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31370566/

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