【问题标题】:Why does this While loop cycle twice?为什么这个 While 循环循环两次?
【发布时间】:2016-10-09 22:19:59
【问题描述】:

我制作了这个 while 循环,它应该满足不同形状的功能,在它满足该形状的功能后,它会一直询问形状,直到用户键入“退出”。到目前为止,我只完成了三角形,所以我只需要完成一些填充函数来确保它正确循环。问题是,在我完成三角形之后,它会在要求输入之前打印菜单两次,而不是只打印一次。谁能给我解释一下?

while(password){
    System.out.println();
    System.out.println("---Welcome to the Shape Machine---");
    System.out.println("Available Options:");
    System.out.println("Circles");
    System.out.println("Rectangles");
    System.out.println("Triangles");
    System.out.println("Exit");
    String option = keyboard.nextLine();

    if(option.equals("Exit")){
        System.out.println("Terminating the program. Have a nice day!");
        return; 
    } else if(option.equals("Triangles")){
        System.out.println("Triangles selected. Please enter the 3 sides:");
        int sideA = 0;
        int sideB = 0;
        int sideC = 0;
        do{
            sideA = keyboard.nextInt();
            sideB = keyboard.nextInt();
            sideC = keyboard.nextInt();

            if(sideA<0 || sideB<0 || sideC<0)
                System.out.println("#ERROR Negative input. Please input the 3 sides again.");
        } while(sideA<0 || sideB<0 || sideC<0);

        if((sideA+sideB)<=sideC || (sideB+sideC)<=sideA || (sideA+sideC)<=sideB){
            System.out.println("#ERROR Triangle is not valid. Returning to menu.");
            continue;
        } else {
            System.out.println("good job!");
        }
    }
}

【问题讨论】:

  • 什么是password,为什么它永远不会在你的循环中重置?

标签: java while-loop iteration


【解决方案1】:

您可能正在使用keyboard.nextLine();。在 while 循环之外的代码中,确保您始终使用 .nextLine() 而不是其他任何东西。

推理:如果你使用.next(),它只会消耗一个单词,所以下次你调用.nextLine()时,它会消耗该行的末尾。

【讨论】:

    【解决方案2】:

    在您说出sideC = keyboard.nextInt() 之后,您键入的回车符(在键入数字之后)仍在输入缓冲区中。然后打印菜单并执行String option = keyboard.nextLine(); 该命令读取并包括它找到的第一个换行符,它是仍在缓冲区中的换行符。 所以option 现在是一个裸换行符,它与“Exit”或“Triangle”不匹配,所以它再次循环并再次打印菜单。

    【讨论】:

      【解决方案3】:

      此问题是由输入缓冲区中的空格、回车符、换行符、换页符等剩余字符引起的。

      由于下一个 keyboard.nextLine() 不匹配任何给定的选项(并且由于在 while 循环的底部没有“else”来处理这种情况),控件进入下一次迭代,再次打印选项。基于输入处理的周围环境,有几个很好的答案可以解决这个问题。

      由于您的意图是跳过所有空格、回车符、换行符、换页符,直到再次获得有效字符串(option),以下代码最适合您的情况.

      System.out.println();
      System.out.println("---Welcome to the Shape Machine---");
      //...
      System.out.println("Exit");
      String option = keyboard.nextLine();
      keyboard.skip("[\\s]*");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 2016-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多