简体   繁体   English

虽然环境仍在继续,但环路仍在继续

[英]While Loop Continues Despite Condition Being Met

Hey everyone so I've been trying to write what should be a really easy counting program for my CS class, but for some reason it keeps spitting back out the "Please enter a number (0 to stop): " prompt and seems to completely disregard the while loop. 嘿大家所以我一直在努力为我的CS课程编写一个非常简单的计数程序,但由于某种原因,它不断吐出“请输入一个数字(0停止):”提示,似乎完全忽视while循环。 If the condition inside the while loop is being met, why does the while loop not stop even if 0 is entered? 如果满足while循环内的条件,为什么即使输入0,while循环也不会停止? I have done C# in the past, but I'm not really familiar with Java's caveats, so if there's anything weird that Java doesn't like me to do let me know. 我以前做过C#,但我并不熟悉Java的注意事项,所以如果Java不喜欢我做任何奇怪的事情,请告诉我。 For a more detailed description of the program, it's supposed to read both negative and positive numbers from the user, output the sum of the negatives and the positives individually, and then take the average. 对于程序的更详细描述,它应该从用户读取负数和正数,分别输出负数和正数的总和,然后取平均值。 (Obviously below is just the problematic piece of code.) (显然下面只是有问题的一段代码。)

 Scanner scanner = new Scanner(System.in);
    double average;
    double numPositive=0.0;
    double numNegative=0.0;
    double input = 0.0;
    do 
    {
        System.out.print("Please enter a number (0 to stop): ");
            input = scanner.nextDouble();   
        if (input < 0.0)
        {
            numNegative += scanner.nextDouble();

        }
        else if (input > 0.0)
        {
            numPositive += scanner.nextDouble();

        }

    } while (Math.abs(input) > 1.0e-6);  // make the tolerance whatever you want.

You never change input after the initial assignment; 在初始分配后你永远不会改变input ; the loop will continue on forever. 循环将永远持续下去。 I think you forgot to call scanner.nextDouble() again. 我想你忘了再次调用scanner.nextDouble()

You're not taking in input after initially retrieving it. 最初检索后你没有收到input

Your scanner.nextDouble() assigns to numNegative and numPositive - neither of which is checked by the while loop. 您的numNegative scanner.nextDouble()分配给numNegativenumPositive - 这两个都没有被while循环检查。

while (input != 0.0)
    {
        System.out.print("Please enter a number (0 to stop): ");
        input = scanner.nextDouble();

        if (input < 0.0)
        {
            numNegative += input;

        }
        else if (input > 0.0)
        {
            numPositive += input;

        }

    }

You are not assigning a value to input anywhere inside your loop. 你是不是值分配给input你的循环内的任意位置。 So, the initial value remains, and the loop won't exit. 因此,初始值仍然存在,循环不会退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM