2

我正在尝试使用扫描仪输入来计算带有数组的 GPA。我认为while循环是最好的,但我不确定。我有一种方法可以尝试从扫描仪输入到阵列中计算 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);
}

}
4

1 回答 1

1

这是扫描仪文档

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

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.");
        }
    }
}
于 2012-05-11T05:26:19.387 回答