使用switch case语句的数学程序
问题描述:
我正在使用方法和开关案例来输入一个简单的程序,这个程序根据用户的输入使用一个人的响应来添加,乘,减或除以调用相应的方法。使用switch case语句的数学程序
我有三个问题:
我的switch语句不工作
程序要求我初始化变量
answer
,但是当我将其设置为0,I不管方程是什么,总是得到0的响应。我的方法没有返回答案,但是当我从方法内输出时,它会显示正确答案。这是我的代码在下面,我的编译错误。
import java.util.Scanner;
public class Math {
public static void main (String[] args){
//used to import scanner class for keyboard use
Scanner kb = new Scanner(System.in);
//used to hold value of first number
int a;
//used to hold the value of the second number
int b;
//used to hold value for response of line 29
int d;
//out put message to user
System.out.println("Please enter a whole number between 0 and 100.");
a = kb.nextInt();
if (a > 100) {
System.out.println("The number you entered did not match the criteria, please run the program again.");
System.exit(0);
} else
System.out.println("Please enter another whole number between 0 and 100.");
b = kb.nextInt();
if (b > 100) {
System.out.println("The number you entered did not match the criteria, please run the program again.");
System.exit(0);
} else
System.out.println("What would you like to do with these two numbers?");
System.out.println("1=Add, 2=Subtraction, 3=Multiply, 4=Divide");
d = kb.nextInt();
switch(d){
case '1':
System.out.println("you choose addition!");
add(a, b);
break;
case '2':
subtract(a, b);
break;
case '3':
multiply(a, b);
break;
case '4':
divide(a, b);
break;
default:
System.out.println("You did not make a valid choice, please run the program again.");
System.exit(0);
}
}
public static int add(int x, int y){
int answer;
answer = x+y;
return answer;
}
public static int subtract(int x, int y){
int answer = x-y;
return answer;
}
public static int multiply(int x, int y){
int answer = x*y;
return answer;
}
public static int divide(int x, int y){
int answer = x/y;
return answer;
}
}
答
你永远设置一个答案变量。你的add,sub,multiple和divide方法返回一个int值,但你永远不会指定它来回答。 例子:
int answer = 0;
answer=add(a, b);
+0
谢谢大家。你们真的帮助我。没有意识到我的switch case声明不适用于那些简单的事情。 – Richard
答
你需要有switch语句是这样的:
switch (d)
{
case 1: // look for the int 1 not the char '1'
System.out.println("you choose addition!");
// also, print out what the methods are returning:
System.out.println("The answer is: " + add(a, b));
break;
case 2:
subtract(a, b);
break;
case 3:
multiply(a, b);
break;
case 4:
divide(a, b);
break;
default:
System.out.println("You did not make a valid choice, please run the program again.");
System.exit(0);
}
旁注:
- 在你的鸿沟方法,你正在做的整数除法,这并不精确。 你可能想考虑用双打做分区并返回一个double。
例如,
public static double divide (int x, int y)
{
double answer = (double) x/(double) y;
return answer;
}
- 你也应该close了扫描仪退出程序之前。
请不要张贴在大写,并尝试格式化您的问题,这样更容易阅读。 –
您应该遵循[样式指南](https://google.github.io/styleguide/javaguide.html),这会使您的代码更具可读性,并且更易于调试。 –
@KevinHooke @KevinHooke对不起,我下次肯定会裁员, – Richard