I would like to use Scanner to scan any number of integer then get the average. Before I stop, I would like to type "END".
The code below has: Exception in thread "main" java.util.InputMismatchException error. That is because I scan a string rather than int type.
How should I solve this problem?
Thanks
public static int scanaverage()
{
System.out.println("Enter any number, type 'END' to exit");
Scanner input = new Scanner(System.in);
int total=0;
int count = 0;
while (!(input.nextLine().equals("END")))
{
total += input.nextInt();
count += 1;
}
return total / count;
}
input.nextLine()to read the value as a String and then useInteger.parseInt()to convert String to int. useequalsIgnoreCase()check before parsing