Maria
Maria

Reputation: 383

Java - Creating an array from user input

Here is the assignment:

  1. Create an array to store 10 numbers.
  2. Using a loop, prompt the user to enter 10 grades and store them in the array.
  3. Then make another loop that prints the numbers in the array out backwards and adds up the numbers in the array.
  4. Use the sum to calculate the average of the numbers. Print out the average of the numbers.

My code so far:

public static void ar() {

    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);

    for(int i=0; i < grades.length; i++)
        grades[i]=kb.nextDouble();

    double sum=0;

    for(int j=10; j > grades.length; j--)
        sum=sum+grades[j];

    double ave = sum/10;

    System.out.println(ave);
}

However it only prints 0.0 ten times.

Upvotes: 0

Views: 3316

Answers (2)

CollinD
CollinD

Reputation: 7573

Here is an annotated solution indicating what was changed from your initial code. You were definitely on the right track, just a few small issues.

public static void ar() {

    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);

    for(int i=0; i < grades.length; i++)
        grades[i]=kb.nextDouble();

    double sum=0;

    for(int j=9; j >= 0; j--) //Note here that we've changed our condition. It was running zero times before. Additionally it now runs from 9-0, since the last index is 9
        sum=sum+grades[j];

    //Look out for Integer Arithmetic!
    double ave = sum/10.0;

    System.out.println(ave);
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

The bounds in your for loop to iterate backwards were wrong. You mean to use for (int j=10; j>=0; j--). Try this code:

public static void ar() {
    double[] grades = new double[10];
    Scanner kb = new Scanner(System.in);
    for (int i=0; i<grades.length; i++)
        grades[i] = kb.nextDouble();

    double sum = 0;

    for (int j=grades.length-1; j>=0; j--)
        sum = sum + grades[j];

    double ave = sum / 10;
    System.out.println(ave);
}

Upvotes: 3

Related Questions