I'm trying to make a program that lets the user to input 10 integers, and then calculate the average of that integers. I got Unreachable code
error in System.out.println("average : " + average);
line.
I already try to make a new class and call the method to my main method but it seems not a simple way to do that (and also there's still some error that make me more confuse). So I guess I can make a simple program like this. But i'm stuck figuring out what's wrong with the code. Here's the code.
package nomer15;
import java.util.Scanner;
public class averag {
public static void main(String[] args) {
System.out.println("Enter 10 integers : ");
double average;
int sum = 0;
Scanner sc = new Scanner(System.in);
int numbers[] = new int[10];
for(int i = 0; 1 < 10; i++){
numbers[i] = sc.nextInt();
sum = sum + numbers[i];
average = sum/10;
}
System.out.println("average : " + average); // (Unreachable code error)
}
}
Can you figure out what I did wrong? Thank you.
In addition to your loop test being incorrect (1
is always less than 10
), you should calculate the average after the loop. And you shouldn't use integer math. Finally, I would prefer numbers.length
to the magic 10
. Something like
public static void main(String[] args) {
int[] numbers = new int[10];
System.out.printf("Enter %d integers : ", numbers.length);
int sum = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
sum += (numbers[i] = sc.nextInt());
}
double average = sum / (double) numbers.length;
System.out.println("average : " + average);
}