import java.util.* ;
class Main {
public static double op(String operation, double number1, double number2) {
double x = 0;
if (operation == "+") {
x = number2 + number1;
}
else if (operation == "x" || operation == "*") {
x = number1 * number2;
}
else if (operation == "/" || operation == "÷") {
x = number1 / number2;
}
else if (operation == "-") {
x = number1 - number2;
}
else {
System.out.println("Error: Please re-execute the program and try again!");
}
return x;
}
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
System.out.println("Please enter a number...");
double x = input.nextDouble();
System.out.println("Please enter an operation.... +, -, /, *");
String y = input.next();
System.out.println("Please enter your other number...");
double z = input.nextDouble();
System.out.println(op(y, x, z));
}
}
我希望此函数在执行操作时返回正确的值。但是,它始终返回0分配的初始值。请帮忙!!!
答案 0 :(得分:0)
字符串比较应始终使用equals完成以下代码: -
public static double op(String operation, double number1, double number2) {
double x = 0;
if (operation.equals("+")) {
x = number2 + number1;
}
else if (operation.equals("x") || operation.equals("*")) {
x = number1 * number2;
}
else if (operation.equals("/") || operation.equals("÷")) {
x = number1 / number2;
}
else if (operation.equals("-")) {
x = number1 - number2;
}
else {
System.out.println("Error: Please re-execute the program and try again!");
}
return x;
}
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
System.out.println("Please enter a number...");
double x = input.nextDouble();
System.out.println("Please enter an operation.... +, -, /, *");
String y = input.next();
System.out.println("Please enter your other number...");
double z = input.nextDouble();
System.out.println(op(y, x, z));
}