[英]How to loop only when say yes/continue. My code just keep looping and don't care about boolean I code
I need to write code and in the end, the user can choose to continue or stop.我需要编写代码,最终用户可以选择继续或停止。 But after try and error for many times, I just can't find the solution.
但是经过多次尝试和错误,我就是找不到解决方案。 It just keep looping.
它只是不断循环。
import java.io.*;
public class medicine {
public static void main(String args[]) throws IOException {
boolean choice;
do {
int age;
String answer = null;
BufferedReader n = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Your Name: ");
String name = n.readLine();
System.out.println("Enter Your Age: ");
age = Integer.parseInt(n.readLine());
System.out.println("Your recomended paracetamol dosage: ");
if (age < 1) {
System.out.println("60 - 120 mg");
} else if ((age >= 1) && (age <= 5)) {
System.out.println("120 - 240 mg");
} else if ((age >= 6) && (age <= 12)) {
System.out.println("240 - 480 mg");
} else {
System.out.println("INVALID AGE, PLEASE REFER TO PHARMACY OR DOCTOR NEAR YOU... THANK YOU");
}
System.out.println("Do You Want to Continue?");
} while (choice = true);
}
}
This is the output.这是输出。 Like you can see, it just looping and don't seem to take any input for yes or no.
如您所见,它只是循环,似乎没有输入是或否。
Enter Your Name:
Nik
Enter Your Age:
12
Your recomended paracetamol dosage:
240 - 480 mg
Do You Want to Continue?
Enter Your Name:
Sarah
Enter Your Age:
10
Your recomended paracetamol dosage:
240 - 480 mg
Do You Want to Continue?
Enter Your Name:
Try to read input from user after your question "do you want to continue" , something like:尝试在您的问题“您想继续吗”之后读取用户的输入,例如:
String choice= n.next();
boolean continue= choice.equalsIngoreCase("yes") || choice.equalsIngoreCase("yes")
and change the condition to while (continue);
while (choice=true)
=
is an assignment, not a comparison. =
是赋值,而不是比较。 You are always setting choice
to true
here, so the condition is always true, and the loop always continues.您总是在此处将
choice
设置为true
,因此条件始终为真,并且循环始终继续。
Use ==
instead;使用
==
代替; or, better, simply use:或者,更好的是,只需使用:
while (choice)
which avoids the possibility of the typo.这避免了错字的可能性。
However, you will then need to tackle the problem that you don't otherwise set the value of choice
: I suppose you have just forgotten to read something from the scanner.但是,您将需要解决您没有以其他方式设置
choice
值的问题:我想您刚刚忘记从扫描仪中读取某些内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.