Dennis Kim Dennis Kim - 7 months ago 15
Java Question

Write methods to test for average grades in java

I'm writing code for homework and I got stuck.

The homework is to write a program to get the average of 10 grades that the user inputs.

I got most of it I believe, but in the

averageGrades
method when I try to declare
average
it wont let me.

This is what I have:

public class Averagegrades
{
public int min, max;
double average;

public static void main (String [] args)
{

double sum = 0;
Scanner scan = new Scanner(System.in);
int [] gradesarray = new int[10];

System.out.println("Please enter the 10 test grades: ");

for (int i = 0; i < gradesarray.length; i++)
{
gradesarray[i] = scan.nextInt();

if(gradesarray[i] > 100)
{
System.out.println("Please enter a number within 0 - 100: ");
gradesarray[i] = scan.nextInt();
}
}

System.out.println("These are the grades you entered: " +
Arrays.toString(gradesarray));
System.out.println("You have entered " + gradesarray.length + " grades");

for(double num : gradesarray)
{
sum = sum + num;
}

System.out.println("This is the sum " + sum);
}

public double averageGrades()
{
average = sum / (double) gradesarray.length;
}

Answer

So this will let you declare avg. The problem is that the method averageGrades could not find sum or gradesarray because those two variables were declared in the main method, and thus not visible to the method.

package test;

import java.util.Arrays;
import java.util.Scanner;

public class Averagegrades 
{
public int min, max;
double average; 
static double sum;
static int[] gradesarray;

public static void main (String [] args)
{
    sum = 0;
    Scanner scan = new Scanner(System.in);
    gradesarray = new int[10];
    System.out.println("Please enter the 10 test grades: ");

    for (int i = 0; i < gradesarray.length; i++)
    {            
        gradesarray[i] = scan.nextInt();
        if(gradesarray[i] > 100)
        {
            System.out.println("Please enter a number within 0 - 100: ");
            gradesarray[i] = scan.nextInt();
        }
    }
    System.out.println("These are the grades you entered: "+
            Arrays.toString(gradesarray));
    System.out.println("You have entered "+gradesarray.length+" grades");

    for(double num : gradesarray)
    {
        sum = sum + num;
    }
    System.out.println("This is the sum "+sum);
}

public double averageGrades()
{
    average = sum / (double) gradesarray.length;
    return average ;
}

Alternative you could have also done...

public double averageGrades(int sum, int[] gradesarray)
{
  average = sum / (double) gradesarray.length; 
  return average ;
}

and then when calling the method...

averageGrades(sum, gradesarray);

By doing this you wouldnt have to move sum and gradesarray declaration outside of the the main method.

Hope this helps!

Comments