gpt4 book ai didi

Java Switch语句: creating a calculator error

转载 作者:行者123 更新时间:2023-12-02 00:47:30 25 4
gpt4 key购买 nike

我想知道是否有人能看出我的代码有什么问题。它可以工作,只是程序不承认我的 switch 语句 - 我搜索了很多问题,但由于我是新手,我显然错过了一些东西。

import java.util.Scanner;
class Calmlr1 {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
String anotherOption = "y", operatorOpt= "a";
int no1=0, no2=0;
double result= 0;
System.out.println ("Welcome to the online calculator! Let's begin...");
while (anotherOption.equalsIgnoreCase ("y")) {
System.out.println ("Please enter your 1st number: ");
no1 = input.nextInt();
System.out.println ("Please confirm your operator:\n1 = +\n2 = - \n3 = *\n4 = /");
operatorOpt = input.next ();
System.out.println ("Please enter your 2nd number: ");
no2 = input.nextInt();

switch(no1) {
case 1:
result=no1+no2;
break;
case 2:
result=no1-no2;
break;
case 3:
result=no1*no2;
break;
case 4:
result=no1/no2;
default:
result = 0 ;
break;
}
System.out.println("Your total calculation is: "+result);
System.out.println("Would you like to do another sum? y/n ");
anotherOption=input.next();
}
}
}

最佳答案

您应该使用switch(operatorOpt)。现在您正在接通第一个号码。

您还需要更改:

intoperatorOpt=0;

operatorOpt = input.nextInt();

也就是说,如果您想保持 switch 语句相同。另请参阅@Daniel Imms 的回答以获取其他错误修复。

关于Java Switch语句: creating a calculator error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632659/

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