![](/img/trans.png)
[英]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.