Wesley
Wesley

Reputation: 11

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

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

Upvotes: 0

Views: 3510

Answers (4)

Rohit Vincent
Rohit Vincent

Reputation: 66

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

Upvotes: 0

Mike
Mike

Reputation: 45

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);

Upvotes: 0

Pragmateek
Pragmateek

Reputation: 13374

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

Upvotes: 0

MrSmith42
MrSmith42

Reputation: 10151

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.

Upvotes: 2

Related Questions