Vian Roy
Vian Roy

Reputation: 1

How to add all the inputs the user entered after entering 0 or negative number?! Using do-while statements

import java.util.Scanner;
public class CashRegisterSimulation {

static Scanner console = new Scanner(System.in);    
    public static void main(String[] args) {

        int total = 0 , num;

        /*
         * Create a program that will ask the user to enter a series of amounts. 
         * Assume that the user is allowed to enter positive numbers only. If the 
         * user entered a value of 0, the program will stop asking for numbers and 
         * should display the sum of the inputs given. Use DO WHILE Loops.
         */

            do
            {
            System.out.print("Enter amount : ");
            num = console.nextInt();
                if(num <= 0)
                {
                    System.out.println("STOP");
                    total = total + num;
                    System.out.println("The total amount is : " + total);
                }
            } while (num > 0);
    }
}

How do I make my program add all the inputs the user entered after entering 0 or negative number?!

Upvotes: 0

Views: 56

Answers (2)

Rajesh
Rajesh

Reputation: 384

Move your total = total + num; inside an if condition and else print stop and the total. That should print the total if input is <=0.

     do
      {
      System.out.print("Enter amount : ");
      num = console.nextInt();
      if(num>0)
      total = total + num;
      else
          {
              System.out.println("STOP");
              System.out.println("The total amount is : " + total);
          }
      } while (num > 0);

Upvotes: 0

Eran
Eran

Reputation: 393801

You want to add to the sum in each iteration for which num > 0:

    do
    {
      System.out.print("Enter amount : ");
      num = console.nextInt();
      if(num > 0)
      {
          total = total + num;
      }
    } while (num > 0);
    System.out.println("STOP");
    System.out.println("The total amount is : " + total);

Upvotes: 1

Related Questions