我目前正在键入一个简单的程序,其中包含方法和一个开关案例,该案例使用人的响应通过调用相应的方法来添加,乘,减或除,具体取决于用户的方法输入。
我有三个问题:
我的切换声明不起作用
程序要求我初始化变量answer
,但当我将其设置为0时,无论方程是什么,我总是得到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;
}
}
答案 0 :(得分:3)
你需要让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);
}
附注:
例如,
public static double divide (int x, int y)
{
double answer = (double) x / (double) y;
return answer;
}
答案 1 :(得分:0)
您永远不会设置答案变量。你的add,sub,multiple和divide方法返回一个int,但你从不指定它来回答。 例如:
int answer = 0;
answer=add(a, b);