1

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.

bnrfly
  • 155
  • 1
  • 2
  • 11

3 Answers3

2

You have a typo in your code looking at the line below:

 for(int i = 0; 1 < 10; i++)

You probably meant the code should be:

 for(int i = 0; i < 10; i++) //replace 1 with i
randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72
2

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);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • this code totally better than mine. Btw why we need `numbers.length`? and can you please explain what this line means? `sum += (numbers[i] = sc.nextInt());` – bnrfly Apr 28 '16 at 05:31
  • I would prefer `numbers.length` because this way you change `new int[10]` to `new int[20]` or `new int[5]` and the code still works. Assign `sc.nextInt()` to `numbers[i]` add that same value to `sum`. – Elliott Frisch Apr 28 '16 at 05:39
0

Turns out the failure in for(int i = 0; 1 < 10; i++) I didnt realize that I put 1 instead of i there. Now it works like a charm after I initialize average

bnrfly
  • 155
  • 1
  • 2
  • 11