- You do not need
Scanner#hasNextInt
for Scanner(System.in)
. Also, you do not need the check, if (isAnInt)
. Instead, you should put a try-catch
block.
- You should not close
Scanner(System.in)
; otherwise, there is no way to open it again without restarting the JVM.
Both the above thing are required when you use the Scanner
for a File
.
Demo:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
inputThenPrintSumAndAverage();
}
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
long average = 0;
while (true) {
try {
int number = scanner.nextInt();
sum += number;
count++;
} catch (InputMismatchException e) {
break;
}
}
average = Math.round((sum / count));
System.out.println("SUM = " + sum + " AVG = " + average);
}
}
A sample run:
2
3
5
8
abc
SUM = 18 AVG = 4
Note: you can get a better precision for average if you declare it as double
and store the floating-point calculation into it without rounding e.g.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
inputThenPrintSumAndAverage();
}
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
double average = 0;
while (true) {
try {
int number = scanner.nextInt();
sum += number;
count++;
} catch (InputMismatchException e) {
break;
}
}
average = (double) sum / count;
System.out.println("SUM = " + sum + " AVG = " + average);
}
}
A sample run after this change:
2
3
5
8
abc
SUM = 18 AVG = 4.5
It will also be useful for you to understand this concept.