在java中使用while循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18038533/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:58:56  来源:igfitidea点击:

Using while loop in java

javaloopswhile-loop

提问by Neo

I'm trying to read in and add up (only) positive integers until a negative integer is entered. The program is supposed to stop only when a negative integer is entered. The best I've been able to come up with is the code below but the problem is it doesn't stop even when a negative integer is read. PS: I'm still learning so please bear with me. I've tried adding && input2!<0to the while loop condition but it comes up as an error. Any suggestions as to how I can make it behave the way I want it to? Thanks.

我正在尝试读取并添加(仅)正整数,直到输入负整数。该程序应该仅在输入负整数时停止。我能想到的最好的是下面的代码,但问题是即使读取负整数它也不会停止。PS:我还在学习,所以请多多包涵。我尝试添加&& input2!<0到 while 循环条件,但它作为一个错误出现。关于如何让它按照我想要的方式行事的任何建议?谢谢。

public class Total{
    public static void main(String[] args){

            System.out.println("Enter an integer: ");

            Scanner entry = new Scanner(System.in);
            int input1 = entry.nextInt();

            System.out.println("Enter another integer: ");
            int input2 = entry.nextInt();

            int total = input1 + input2;

            while (input2 > 0){            
                System.out.println(total + "\nEnter another interger:  ");
                total += entry.nextInt();
            }
    }
}

回答by Hovercraft Full Of Eels

You need to change the variable that is being tested, here input2, insideof the loop. Else there's no chance of exiting. All you change in the loop is the total variable while input2 remains unchanged, and so every time it is tested, it remains >0 and that's why you're stuck. Why not give it another try, this time changing input2 (and still changing total as well, using input2), and see if you can't get it.

您需要在循环内部更改正在测试的变量,此处为 input2 。否则没有机会退出。您在循环中更改的只是 total 变量,而 input2 保持不变,因此每次测试时,它都保持 > 0,这就是您被卡住的原因。为什么不再试一次,这次改变 input2(并且仍然改变 total ,使用 input2),看看你是否能得到它。

回答by Prem

The number you accept inside the loop is not storing into the input2 variable. So the program will never exit.By the way you don't even need input2. variable input1 is enough. See the sample program below:

您在循环内接受的数字未存储到 input2 变量中。所以程序永远不会退出。顺便说一下,你甚至不需要input2。变量 input1 就足够了。请参阅下面的示例程序:

public static void main(String[] args){


            System.out.println("Enter an integer: ");

            Scanner entry = new Scanner(System.in);
            int input1 = entry.nextInt();


            int total =input1;

            while (input1 > 0){
                System.out.println(total + "\nEnter another interger:  ");
                input1 = entry.nextInt();
                total += input1;

            }
    }

回答by Pandacoder

Your input1 and input2 being added in directly kind of defect the purpose of quitting on the first entered negative number, but the code I displayed below works. It will only prompt the user for any additional numbers if the number entered is non-negative, and it will only sum the entered number if the number is non-negative.

您的 input1 和 input2 被直接添加到某种缺陷中,目的是在第一个输入的负数上退出,但我在下面显示的代码有效。如果输入的数字为非负数,它只会提示用户输入任何其他数字,如果数字为非负数,它只会对输入的数字求和。

package stackoverflow.answers;

import java.util.Scanner;

public class Total {
    public static void main(String[] args) {
        int total = 0, input = 0;

        /* Print out your "request" for an integer
         * so the user knows to enter something.
         */
        System.out.print("Enter an integer: ");

        /* Create a Scanner on the System.in stream */
        Scanner entry = new Scanner(System.in);

        /* Loop while the entered number is > 0 */
        while ((input = entry.nextInt()) > 0) {
            /* If the input > 0, add it to total */
            total += input;

            /* Print out the request again. */
            System.out.print("Total: " + total + "\nEnter an integer: ");
        }

        /* Just for kicks, print out the total
         * (only useful if the first entered number
         * is negative and the total would be 0). */
        System.out.println("Total: " + total);
    }
}

If you want to sum the negative number, and THEN quit, I suggest changing the while loop to a do-while loop, like this:

如果您想对负数求和,然后退出,我建议将 while 循环更改为 do-while 循环,如下所示:

        /* Get an integer and add it to the sum, and
         * then loop while the entered number is > 0 */
        do {
            /* Get the integer */
            input = entry.nextInt();

            /* If the input > 0, add it to total */
            total += input;

            /* Print out the request again. */
            System.out.print("Total: " + total + "\nEnter an integer: ");
        } while (input > 0);

回答by Sidarth

public class WhileLoopExample {

    public static void main(String[] args) {

        int i=1;
        System.out.println("While Loop Demo");
        while(i<=10){
            System.out.println(i);
            i++;
        }
    }
}

回答by Shubham Agrawal

int input1 = entry.nextInt();

        System.out.println("Enter another integer: ");
        int input2 = entry.nextInt();

        int total = input1 + input2;

        while (input2 > 0){            
            System.out.println(total + "\nEnter another interger:  ");
            total += entry.nextInt();

In last line you are directly taking the input without checking its positivity you are directly adding it to total. Also, in while loop your condition is while(input2>0). Suppose your input2 gets a positive value then the while loop will never end. So make the change by replacing the code with below code

在最后一行中,您直接接受输入而不检查其积极性,您将其直接添加到总数中。此外,在 while 循环中,您的条件是while(input2>0). 假设您的 input2 获得一个正值,那么 while 循环将永远不会结束。因此,通过用下面的代码替换代码来进行更改

int input1 = entry.nextInt();

             if(input1>0)
            int total =input1;

                while (input1 > 0){
                System.out.println(total + "\nEnter another interger:  ");
                input1 = entry.nextInt();
                    if(input1>0)
                total += input1;
               }

回答by Prince Gera

while(Boolean_expression) {
   // Statements
}

Boolean_expression like true/false;

Boolean_expression 像真/假;

// Statements like     System.out.prinln("Jai Shree Ram");