gpt4 book ai didi

使用 switch case 的 Java 计算器

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

我的要求 - calc 方法应该从 main 中获取两个数字,并且 calc 将执行所有操作。一切都很顺利,直到 switch 命令出现问题。我收到错误“选择无法解析为变量”。

import java.util.Scanner;

public class Learn {

public static void main(String args[]) {
int firstnumber, secondnumber, choice;

System.out.println("1- Add");
System.out.println("2- Sub");
System.out.println("3- Div");
System.out.println("4- Mul");
System.out.print("Enter your choice -");
Scanner var = new Scanner(System.in);

choice = var.nextInt();
System.out.print("Enter first number -");
firstnumber = var.nextInt();
System.out.print("Enter second number -");
secondnumber = var.nextInt();
calc(firstnumber, secondnumber);
}

public static void calc(int x, int y) {
int c;

switch (choice) {
case 1:
c = x + y;
System.out.print("Output-" + c);
break;

case 2:
c = x - y;
System.out.print("Output-" + c);
break;

case 3:
c = x / y;
System.out.print("Output-" + c);
break;

case 4:
c = x * y;
System.out.print("Output-" + c);
break;
}
}
}

我缺少什么,如何解决这个问题?

最佳答案

由于 choice 是不同函数中的本地函数,因此您需要将其作为参数传递:

public static void calc(int x, int y, int choice) {
...
}
...
calc (firstnumber,secondnumber, choice);

请注意,您的 calc 方法不是最佳的:所有四个 case 中都有相同的行:

System.out.print("Output-" + c);

您可以将此行移至switch 之后,并添加默认情况以在选择无效时引发异常。

关于使用 switch case 的 Java 计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26692689/

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