[英]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*/
}
}
For some reason, it won't take into account the other variables under the same names.出于某种原因,它不会考虑同名下的其他变量。 I've tried changing where the variable is read weather its the top or the bottom but I get the same outcome.
我尝试更改读取变量的位置,使其处于顶部或底部,但得到相同的结果。
You need to change你需要改变
} while (b=true);
To到
} while (b==true);
or simply或者干脆
} while (b);
The reason is that =
is the set operator, and ==
is checking for equality原因是
=
是集合运算符,而==
是检查相等性
do {
String f = scan.nextLine();
if (f == "yes") {
b = true;
} else {
b = false;
}
} while(b=true);
}
As others have pointed out, the problem is that you're assigning b=true
immediately before checking if b
is true, is you're always going to continue looping.正如其他人指出的那样,问题在于您在检查
b
是否为真之前立即分配b=true
true ,您是否总是要继续循环。
But there's a problem before that too: that's not how you check for string equality:但在此之前也存在一个问题:这不是检查字符串相等性的方式:
if (f.equals("yes")) {
b = true;
} else {
b = false;
}
Or, easier:或者,更简单:
b = f.equals("yes");
and update the loop condition to并将循环条件更新为
} while (b);
Or, even easier again (because it doesn't involve an extra variable):或者,更容易(因为它不涉及额外的变量):
if (!f.equals("yes")) break;
And use while (true)
as the loop condition.并使用
while (true)
作为循环条件。
While loop use to check the condition not for assigning the values to parameters. While 循环用于检查条件,而不是将值分配给参数。
while(b=true);
Here you are assigning value to be instead of checking the condition.在这里,您正在分配值而不是检查条件。 You can use either of these solutions.
您可以使用这些解决方案之一。
while(b==true);
or要么
while(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.