[英]I'm trying to Run this program on eclipse but get this error in console
[英]I'm trying to get the loop to run on the conditions of b but it wont read it
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws InterruptedException {
boolean b = true;
do {
Scanner scan = new Scanner(System.in);
System.out.println("please enter a number to calculate the collatz conjecture ");
String userNumber = scan.nextLine();
int Number = Integer.parseInt(userNumber);
do {
double SecondNumber = (double) Number;
if (SecondNumber / 2 != Number / 2) {
Number = Number * 3 + 1;
System.out.println(Number);
}
if (SecondNumber / 2 == Number / 2) {
Number = Number / 2;
System.out.println(Number);
}
Thread.sleep(250);
} while (Number > 1);
System.out.println("Would you like to run this program again? if so type yes then press enter");
String f = scan.nextLine();
if (f == "yes") {
b = true;
} else {
b = false;
}
} while(b=true); /*for example this reads the first b without taking into account the other ones in between*/
}
}
出於某種原因,它不會考慮同名下的其他變量。 我嘗試更改讀取變量的位置,使其處於頂部或底部,但得到相同的結果。
你需要改變
} while (b=true);
到
} while (b==true);
或者干脆
} while (b);
原因是=
是集合運算符,而==
是檢查相等性
do {
String f = scan.nextLine();
if (f == "yes") {
b = true;
} else {
b = false;
}
} while(b=true);
}
正如其他人指出的那樣,問題在於您在檢查b
是否為真之前立即分配b=true
true ,您是否總是要繼續循環。
但在此之前也存在一個問題:這不是檢查字符串相等性的方式:
if (f.equals("yes")) {
b = true;
} else {
b = false;
}
或者,更簡單:
b = f.equals("yes");
並將循環條件更新為
} while (b);
或者,更容易(因為它不涉及額外的變量):
if (!f.equals("yes")) break;
並使用while (true)
作為循環條件。
While 循環用於檢查條件,而不是將值分配給參數。
while(b=true);
在這里,您正在分配值而不是檢查條件。 您可以使用這些解決方案之一。
while(b==true);
要么
while(b);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.