Java GPA阵列扫描器输入和计算

时间:2012-05-11 03:57:26

标签: java arrays loops methods user-input

我正在尝试使用扫描仪输入来计算带阵列的GPA。我认为一段时间循环是最好的,但我不确定。我有一种方法可以尝试从扫描仪输入到阵列中计算GPA。我的代码已附上。让我知道最简单的方法是什么。

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);
}

}

1 个答案:

答案 0 :(得分:1)

这是Scanner documentation

经过快速测试后,这似乎有效:

import java.util.Scanner;

class ClassNamesShouldBeCapitalized
{
    public static void main(String[] args)
    {
        Scanner gradeScanner = new Scanner(System.in);

        int gradeCounter = 0;
        int gradeTotal = 0;

        System.out.println("Input grade: " );

        while(gradeScanner.hasNextInt()) {
            int nextGrade = gradeScanner.nextInt();
            System.out.println("Recorded grade: " + nextGrade);
            System.out.println("Input grade: " );
            gradeTotal += nextGrade;
            gradeCounter++;
        }

        if (gradeCounter > 0) {
            double avg = gradeTotal / gradeCounter;
            System.out.println("Here's your average: " + avg);
        }
        else {
            System.out.println("No grades found.");
        }
    }
}