0
我想根据用户输入创建一个结果(result1)。我收到一个错误,说result1可能没有启动。如果我通过输入int result1 = 0;
将它添加到上面的代码中,我的if-then-else语句导致system.out.println(result1);
每次都会给我一个0的结果。它完全跳过了我的if-then-else语句。一旦用户输入一个字符串,不应该立即启动result1吗?我很感谢能给出的任何建议或见解。比较字符串时扫描仪&if-then-else问题
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc0 = new Scanner(System.in);
System.out.print("What would you like to do?: (A)Addition (B)Subtraction (C)Multiplication (D)Division: ");
String input0 = sc0.nextLine();
Scanner sc1 = new Scanner(System.in);
System.out.print("Enter a number: ");
String input1 = sc1.nextLine();
Scanner sc2 = new Scanner(System.in);
System.out.print("Enter a number: ");
String input2 = sc2.nextLine();
int int1 = Integer.parseInt(input1);
int int2 = Integer.parseInt(input2);
if (input0 == "A")
{
result1 = int1 + int2;
}
else if (input0 == "B")
{
result1 = int1 - int2;
}
else if (input0 == "C")
{
result1 = int1 * int2;
}
else if (input0 == "D")
{
result1 = int1/int2;
}
else {
System.out.println("You have entered an invalid option.");
System.exit(0);
}
System.out.println("Your result is, " + result1 + "!");
}
}
在Java中,应先声明变量,然后才能使用它。初始化您的int结果= 0并使用.equals而不是==进行字符串比较。 – imprezzeb
当我使用single =时,java给了我一个期望布尔值的错误。我如何避免这种情况? – Izlix
这是因为单个(=)等号被用作赋值运算符。请检查我的答案下面的正确字符串比较。 – imprezzeb