使用if语句检查While循环

时间:2015-12-08 17:52:19

标签: java if-statement while-loop

while循环和if语句完成第一次迭代。完成后,它打印出“你还想要另一次吗?”我输入“Y”程序终止,我不知道为什么。我的逻辑和语法似乎是正确的,但总有一些我无法用自己的眼睛看到的缺陷。如果有人可以指出这个缺陷,我将不胜感激。

awk 'FNR == NR{print "1st pass"; next}
     {print "second pass"}' x.txt x.txt

3 个答案:

答案 0 :(得分:0)

你不应该检查缓冲区中是否有另一行;您可以通过str明确检查您返回的输入。您第一次退出循环的可能原因是in.hasNextLine()为假。

因此,这意味着您要将if声明更改为:

if(str.equals("Y")) {

}

答案 1 :(得分:0)

已经读取之后,您正试图查看是否有下一行(in.hasNextLine())。

尝试这种方式:

       while (!check) {
            if(in.hasNextLine()){
                System.out.println("Do you want another time?");
                str = in.nextLine();
                if("Y".equals(str)){
                    hours = ran.nextInt(11) + 1;
                    minutes = ran.nextInt(60);
                    if (minutes < 10) {
                        System.out.println(hours + ":" + "0" + minutes);
                    } else {
                        System.out.println(hours + ":" + minutes);
                    }
                    System.out.println("Do you want another time?");
                }
            }else{
                check = true;
            }
        }

好的,这是一个更好的方法来完成这一切:

while (in.hasNextLine()) {
        System.out.println("Do you want another time?");
        if("Y".equals(in.nextLine())){
            //do what you want to do
        }else{
          //perhaps you want to break, or whatever you want to do
          break;
        }
    }

答案 2 :(得分:0)

这就是你要找的东西。

while (!check) {        

        hours = ran.nextInt(11) + 1;
        minutes = ran.nextInt(60);

        if (minutes < 10) {
            System.out.println(hours + ":" + "0" + minutes);
        } 
        else {
            System.out.println(hours + ":" + minutes);
        }

        System.out.println("Do you want another time?");
        str = in.nextLine();

        if(str.equals("Y"))
          check = false;
        else
        check = true;   

}

我改变的是,我在输入后比较str。 如果它的“Y”它将继续,否则它将退出while循环。

相关问题