How to sum up the resultes in a while loop while centain input will end the while loop?

北战南征 提交于 2019-12-12 02:25:48

问题


I have a situation in java;

I would like to ask the user to put in some numbers & have a total of those numbers. However if the user enter a negative number it will end the loop;

currently I have a while loop as below;

                double sum = 0;
    double Input = 0;
    System.out.println("Please enter the numbers (negative to end)")
    System.out.println("Enter a number");
    Scanner kdb = new Scanner(System.in);
          Input = kdb.nextDouble();
    while (Input > 0)
    {
        System.out.println("Enter an income");
        Input = kdb.nextDouble();
        sum = Input;
    }

However it does not do the job. If the user put in 40,60,50, and -1 the correct result should be 150; my loop result in 109.

Please help!

Many thanks! Jackie


回答1:


double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)")
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
Input = kdb.nextDouble();
while (Input > 0)
{
    sum += Input;
    System.out.println("Enter an income");
    Input = kdb.nextDouble();
}

I recommend variable names not to start with upper case letters.




回答2:


You should check for Input > 0 before doing sum += Input.




回答3:


This should work!

        double sum = 0;
    double Input = 0;
    boolean Adding= true;
    System.out.println("Please enter the numbers (negative to end)");

    Scanner kdb = new Scanner(System.in);
    while(Adding == true)
    {
        System.out.print("Enter a number: ");
        Input = kdb.nextDouble();
        if(Input > 0)
        {
            sum+= Input;
        }
        else
            Adding = false;

    }
    System.out.println("Your sum is: " + sum);



回答4:


The first input value was overwritten by the second one since the the sum was done only at the end of the loop.

**double sum = 0;
double Input = 0;
System.out.println("Please enter the numbers (negative to end)");
System.out.println("Enter a number");
Scanner kdb = new Scanner(System.in);
      Input = kdb.nextDouble();
while (Input>0)
{
    sum+= Input;
    System.out.println("Enter an income");
    Input = kdb.nextDouble();

}
System.out.println(sum);
}**

The output is:

Please enter the numbers (negative to end)

Enter a number 40 Enter an income 50 Enter an income 60 Enter an income -1 150.0



来源:https://stackoverflow.com/questions/14178159/how-to-sum-up-the-resultes-in-a-while-loop-while-centain-input-will-end-the-whil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!