[英]Getting out of while-loop with switch-statement
I was trying to make a program which reads your temperature, gives you a feedback as to how good it is, above, under or inbetween the average bodytemperature. 我试图制作一个程序来读取您的体温,为您提供有关体温在平均体温之上,之下或中间的好坏的反馈。 After this I want the program to ask the user whether he/she wants to do another reading, by input.
在此之后,我希望程序通过输入来询问用户他/她是否要再次阅读。 For this I use a switch-statement.
为此,我使用了一个切换语句。 It almost works fine: the user input y, the program loops again and all is jolly good.
几乎可以正常工作:用户输入y,程序再次循环,一切都很好。 However, when the user input n, the program still restarts?
但是,当用户输入n时,程序仍然重新启动? Can anyone help me as to why this is happening?
谁能帮我了解为什么会这样?
The code: 编码:
import java.util.*;
class Uke2Ekstra17{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
boolean lokke=true;
while(lokke=true){
System.out.println("Vennligst oppgi temperaturen din, så skal du få vite om du ligger over, under eller innenfor gjennomsnittstemperaturen! Skriv her: ");
double temp=input.nextDouble();
if(temp<36.5){
System.out.println("Du ligger under gjennomsnittet med " + (36.5-temp) + " grader.");
}else if(temp>36.5 && temp<37.5){
System.out.println("Du ligger innenfor gjennomsnittstemperaturen.");
}else{
System.out.println("Du ligger over gjennomsnittet med " + (temp-37.5) + " grader.");
}
System.out.println("Vil du gjøre en ny maaling? y/n: ");
char svar=input.next().charAt(0);
switch(svar){
case 'y':
lokke=true;
break;
case 'n':
lokke=false;
break;
}
}
}
}
Your boolean while (lokke=true)
is assigning lokke
, not checking it. 您的布尔值
while (lokke=true)
分配了 lokke
,而不进行检查。 It should be a ==
. 它应该是
==
。 If you're checking a boolean though, you don't need to compare it to true
or false
explicitly. 如果您要检查布尔值,则无需将其显式比较为
true
或false
。 You can use while (lokke)
您可以使用
while (lokke)
This statement 这个说法
while (lokke=true) {
always evaluates to true
as assignments always evaluate to their right hand side value. 总是评估为
true
因为赋值总是评估为右侧值。 Instead use 改为使用
while(lokke == true) {
or simply 或简单地
while (lokke) {
Another option would be create an infinite loop, and break it, so you wouldn't even need lokke
variable.- 另一个选择是创建一个无限循环,然后将其中断,因此您甚至不需要
lokke
变量。
while(true) {
//...
if (svar == 'n') {
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.