當用戶輸入 true 時,代碼不會輸出 Suspended,而是輸出 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");
}
}
}
uj5u.com熱心網友回復:
你使用=不當。在您的示例中,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
}
PS我認為你也混淆了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");
}
uj5u.com熱心網友回復:
問題出在這條線上:
if(isSuspended = true) {
它應該是
if(isSuspended == true) {
甚至:
if(isSuspended) {
isSuspended = true(使用 one =)為變數分配一個新值,isSuspended覆寫用戶輸入的任何內容。
在 Java 中,這些值分配被視為一個值:isSuspended = true具有值true(所以在任何地方你可以放置一個類似trueor的布林值,你也可以放置一個類似orfalse的運算式,它也像一個布林值,但具有“副作用”給變數賦值)。yourVariableName = truemyVariable = false
如果要比較一個值是否相等,則需要使用==(或.equals(...)用于字串和其他物件)。如果要檢查布林值是否為true,則甚至不需要== true,因為該比較的值最終將是trueor false,這正是您要比較的布林值最初具有的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416327.html
標籤:
