java 布尔 Do-While 循环永不停止
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14223436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boolean Do-While Loop Never Stops
提问by Damion Deslaurier
This is the working product of what everyone told me to do. Thanks guys, i'll try to keep my code cleaner from now on. This code is just practice and is eventually just going to be a lock-out system for my computer that runs on start-up. Who wants pesky preteens messing around on their computer? not this guy.
这是每个人都告诉我要做的工作成果。谢谢大家,从现在开始我会尽量让我的代码更干净。这段代码只是练习,最终将成为我在启动时运行的计算机的锁定系统。谁想要讨厌的青春期前的孩子在他们的电脑上乱搞?不是这个人。
import java.io.*;
import java.util.Scanner; /
class AgeChecker
{
public static void main (String[] args) throws Exception /*@Exception- thrown to allow reading
{ of single characters*/
char ans; //(Read from user input)
String name;
boolean loop = false; //To loop back after a section, add loop = true.
//To stop the program after a section, add loop = false.
do
{
Scanner dd = new Scanner(System.in);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Needed to read the
BufferedReader in1 = new BufferedReader(new InputStreamReader(System.in)); // character input
System.out.println("What is your name? "); name = dd.nextLine();
{
System.out.println("Are you 14 years of age or older? (y/n) "); ans = (char)in.read();
//Using if, else-if and else to make sure
if (ans == 'y') //I have a good grasp of what i already know
{
System.out.println("Welcome, " + name + "! Are you 21 years of age or older? (y/n) ");
ans = (char)in1.read();
if (ans == 'n')
{
System.out.println("Welcome, " + name + "!");
loop = false;
}
else if (ans == 'y')
{
System.out.println("Welcome, " + name + "! Would you like a drink? ");
loop = false;
}
}
else if (ans == 'n')
{
System.out.println("We're sorry. Only those at the age of 14 or older may access this program. ");
loop = false;
}
else
{
System.out.println("Invalid input. ");
loop = true;
}
}
}
}
while (loop == true); //Put here to line up with the 'do' at the top
}
Thanks for the help everyone
感谢大家的帮助
回答by Denys Séguret
Replace
代替
while (fee = true);
with
和
while (fee == true);
or better :
或更好 :
while (fee);
fee = true
is an assignement and returns the assigned value (true
).
fee = true
是一个赋值并返回指定的值 ( true
)。
Replace also
也更换
else
System.out.println("Invalid input. ");
fee = true;
with
和
else {
System.out.println("Invalid input. ");
fee = true;
}
(thanks Rohit).
(感谢罗希特)。
Note that it would be easier (including for you) to fetch those errors if your code had less spaces and less blocks (why so many ?). Those code conventionsmight be useful.
请注意,如果您的代码有更少的空间和更少的块(为什么这么多?),获取这些错误会更容易(包括对您而言)。这些代码约定可能很有用。