布尔Do-While循环永不停止

时间:2013-01-08 20:27:26

标签: java boolean do-while

这是每个人都告诉我要做的工作产品。谢谢你们,我会尽力保持 我的代码清理从现在开始。这段代码只是练习,最终将成为我的计算机在启动时运行的锁定系统。谁想要讨厌的青春期前乱搞他们的电脑?不是这个人。

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
}

感谢大家的帮助

1 个答案:

答案 0 :(得分:7)

替换

while (fee = true);

while (fee == true);

或更好:

while (fee);

fee = true是一个分配并返回指定的值(true)。

也替换

else 
System.out.println("Invalid input. ");
fee = true;

else {
   System.out.println("Invalid input. ");
   fee = true;
}

(谢谢罗希特)。

请注意,如果您的代码具有更少的空间和更少的块(为什么这么多?),那么获取这些错误会更容易(包括你)。那些code conventions可能有用。