0

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.

toco wiy
  • 11
  • 2

1 Answers1

1

Your scanner.hasNextInt() will always return false for any input other than Integer type. Hence that code block is never executed. The count of i will never increase and hence goes to infinite loop.

neeranzan
  • 131
  • 5