I’m trying to use a scanner input to calculate a GPA with an array. I would think a while loop would be best but I’m not sure. I have a method that would attempt to calculate the GPA from the scanner input into the array. My code is attached. Let me know what’s the simplest way to do so.
import java.util.Scanner;
public class gpaArrayInput
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner scan = new Scanner (System.in);
int i = 0;
//double average;
int grades[]=new int [i];
for (i=0; i<grades.length;i++){
System.out.println ("Enter your final class grades for the semester: ");
grades[i]=scan.nextInt();
averageMethod();
}}
public static void averageMethod()
{
double sum=0;
double average;
for(int i=0; i<grades.length;i++)
{
sum += grades[i];
}
average = sum/grades.length;
System.out.println("Your grade average is: "+average);
}
}
Here’s the Scanner documentation.
After a quick test, this seems to work: