I'm trying to write a code using while loop that prompts user to enter any 5 integer numbers. I want the output to display those 5 numbers I entered and as well as the sum of the numbers entered.
My question is: Am I using the while loop correctly or there is any simplified method doing it??
My code:
import java.util.Scanner; public class readinput { public static void main(String[] args){ int count = 0; Scanner input = new Scanner(System.in); System.out.println("Enter 1st number"); int number1 = input.nextInt(); count=count+1; System.out.println("Enter 2nd number"); int number2 = input.nextInt(); count=count+1; System.out.println("Enter 3rd number"); int number3 = input.nextInt(); count=count+1; System.out.println("Enter 4th number"); int number4 = input.nextInt(); count=count+1; System.out.println("Enter 5th number"); int number5= input.nextInt(); count=count+1; while (count==5) { System.out.println("number1: "+number1); System.out.println("number2: "+number2); System.out.println("number3: "+number3); System.out.println("number4: "+number4); System.out.println("number5: "+number5); System.out.println("Sum of all the numbers: "+(number1+number2+number3+number4+number5)); break; } } }
Example my Input are these following number: 2, 6, 1, 3, 7
Output:
number1: 2 number2: 6 number3: 1 number4: 3 number5: 7 Sum of all the numbers: 19