java do while loop with user input

Let’s learn java do while loop with user input.

java do while loop with user input

Now let’s learn to add user input numbers and get total using do while loop.

In the below java program if user inputs 0, do while loop terminates the loop.

Here’s an example.

import java.util.Scanner;
public class DoWhileUserInput
{
   public static void main(String[] args) 
   {
      int number, total = 0;
      Scanner sc = new Scanner(System.in);
      do{
          System.out.println("Please enter number: ");
          number = sc.nextInt();
          total += number;
      }while (number != 0);  
      System.out.println("Total is = " + total);
      sc.close();
   }
}


Output:

Please enter a number: 5
Please enter a number: 1
Please enter a number: 9
Please enter a number: 4
Please enter a number: 2
Please enter a number: 9
Please enter a number: 4
Please enter a number: 0
Total is = 34


Also read – java overview