代码不会输出挂起,而是在用户输入 true 时输出 Won。有人可以帮助解释我对这段代码做错了什么吗?
public class Main {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
boolean isSuspended = read.nextBoolean();
int ourScore = read.nextInt();
int theirScore = read.nextInt();
if(isSuspended = true){
if(ourScore > theirScore){
System.out.println("Won");
} if(ourScore < theirScore){
System.out.println("Lost");
} if(ourScore == theirScore){
System.out.println("Draw");
}
} else {
System.out.println("Suspended");
}
}
}
你用错了=
。在您的示例中,if(isSuspended = true) {}
表示:
boolean isSuspended = read.nextBoolean();
//...
isSuspended = true;
if(isSuspended) {} // it will be always true
要不分配但检查,应改用==
。
if (isSuspended == true) {
// if true
} else {
// if false
}
或更好:
if (isSuspended) {
// if true
} else {
// if false
}
附言我想你也混淆了 if 案例。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean suspended = scan.nextBoolean();
int ourScore = scan.nextInt();
int theirScore = scan.nextInt();
if (suspended)
System.out.println("Suspended");
else if (ourScore > theirScore)
System.out.println("Won");
else if (ourScore < theirScore)
System.out.println("Lost");
else
System.out.println("Draw");
}
问题出在以下行上:
if(isSuspended = true) {
它应该是
if(isSuspended == true) {
甚至:
if(isSuspended) {
isSuspended = true
(带有一个=
)为变量分配一个新值isSuspended
覆盖用户输入的任何内容。
在 Java 中,这些值赋值被视为值:isSuspended = true
具有值true
(因此您可以在任何地方放置像true
或false
这样的布尔值,你也可以放置一个像yourVariableName = true
或myVariable = false
这样的表达式,它们也像布尔值一样,但具有为变量赋值的"副作用")。
如果要比较相等的值,则需要使用==
(或字符串和其他对象的.equals(...)
)。如果你想检查一个布尔值是否true
,你甚至不需要== true
,因为该比较的值最终将是true
或false
,这只是你想要比较的布尔值最初具有的值。