GPA计算器以十进制格式

时间:2014-10-25 10:28:43

标签: java decimalformat

我有一个程序,应该将你的gpa列出到两个最接近的小数位,我已经把它归结为最后一行,但是我收到一条错误消息说&# 34;非静态方法格式(double)不能从静态上下文中引用"这是我的代码

import java.text.DecimalFormat;
import java.util.Scanner;

public class GPACalculator {
    public static void main(String[] args) {
        double creditHours = 0;
        double gradePoints = 0;

        System.out.println("Enter number of classes");
        Scanner scanner = new Scanner(System.in);
        double numClass = scanner.nextInt();
        DecimalFormat df = new DecimalFormat("#0.00");

        for(double i = 1; i <= numClass; i++){
            System.out.println("Enter credit hours for class "+ i);
            double aCreditHour = scanner.nextInt();
            creditHours += aCreditHour;
            System.out.println("Enter grade for class "+ i);
            String letter = scanner.next();
            if(letter.equals("A")){
                gradePoints = gradePoints + (4 * aCreditHour);
            } else if (letter.equals("B")){
                gradePoints = gradePoints + (3 * aCreditHour);
            } else if (letter.equals("C")){
                gradePoints = gradePoints + (2 * aCreditHour);
            } else if (letter.equals("D")){
                gradePoints = gradePoints + (1 * aCreditHour);
            } else if (letter.equals("F")){
                gradePoints = gradePoints + (0 * aCreditHour);
            }
        }

        System.out.println("Your GPA is: " + DecimalFormat.format(gradePoints / creditHours));
    }
}

我知道问题出在DecimalFormat之后的.format位,我只是不知道如何修复它。我有点希望知道我应该用

替换它

1 个答案:

答案 0 :(得分:0)

首先实例化DecimalFormat:

    DecimalFormat dFormat = new DecimalFormat();
    System.out.println("Your GPA is: " + dFormat.format(gradePoints/creditHours));

您直接调用非静态方法(DecimalFormat.format),这是不可能的!只能以这种方式调用静态方法,另一种方法是实例化它们并通过instance.method()调用它们!