Simple program of Java that should 5 integers from user, and should check if they are integers, then find the sum of 5 integers. And if input is other than integer, Show INVALID INPUT, and then ask again for the correct input. Display the sum at the end
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i=0,sum=0;
Scanner scanner= new Scanner (System.in);
System.out.println("Enter 5 numbers: ");
while (i<5){
System.out.print("Enter number #" + (i+1) + " : ");
if(scanner.hasNextInt()){
sum=sum+scanner.nextInt();
i++;
}
else
System.out.println("Invalid Number");
}
System.out.println("Sum of numbers is " + sum);
scanner.close();
}
}
whenever anything other than Integer is entered, it goes into infinite loop.