为什么我很简单的while循环重复一个额外的时间?

时间:2018-06-20 16:47:12

标签: java loops while-loop extra

这是我的while循环。该程序对整数求和,直到输入负数。到那时,循环应该中断,并且应该打印“再见”。但是,它会在每次道别之前添加负数。我不确定这里出了什么问题。请帮忙?!

import java.util.Scanner;

public class While {
    public static void main(String[] args)
    {
        int input = 5;
        int sum = 0;

        while(input >= 0)
        {
            System.out.println("Please enter a positive integer: ");
            Scanner in = new Scanner (System.in);
            input = in.nextInt();
            sum = sum + input;
            System.out.println("Running total: " + sum );
        }

        System.out.println("Goodbye!" );
    }

测试:

Please enter a positive integer: 

5

Running total: 5

Please enter a positive integer: 

10

Running total: 15

Please enter a positive integer: 
-1

Running total: 14

Goodbye!

我不想获得14的返回值,只应该说再见!

2 个答案:

答案 0 :(得分:1)

您需要使用break关键字。您的循环将始终结束,因此while的检查仅在您添加负数之后进行。您可以更改为此:

        while(true)
        {
            System.out.println("Please enter a positive integer: ");
            Scanner in = new Scanner (System.in);
            input = in.nextInt();
            if(input <0){
                break;
            }
            sum = sum + input;
            System.out.println("Running total: " + sum );
        }

或者这个:

while(input >= 0)
            {
                System.out.println("Please enter a positive integer: ");
                Scanner in = new Scanner (System.in);
                input = in.nextInt();
                if(input <0){
                    break;

                    sum = sum + input;
                    System.out.println("Running total: " + sum );
                }
            }

或完全避免if语句在需要时使用(尽管这不是循环的重点):

while(input >= 0)
                {
                    sum = sum + input;
                    System.out.println("Please enter a positive integer: ");
                    Scanner in = new Scanner (System.in);
                    input = in.nextInt();

                    System.out.println("Running total: " + sum );

                }

答案 1 :(得分:1)

这是我的解决方法:

while(input >= 0)
        {
            sum = sum + input;
            System.out.println("Running total: " + sum );
            System.out.println("Please enter a positive integer: ");
            Scanner in = new Scanner (System.in);
            input = in.nextInt();

        }
        System.out.println("Goodbye!" );
    }
通过在初始化时和输入第一个整​​数之前计算总和。它似乎按照我现在想要的方式工作。感谢您的帮助。