双重未在方法之间传递

双重未在方法之间传递

我设计了一个小程序,其中有三个考试成绩,并使用“成绩”类计算这三个成绩的平均值。另外,我会提示您输入考试编号(1、2或3),并且应该返回该编号。但是,我的平均考试成绩和所选考试成绩的输出始终为0.0。

package GradesClass;
import java.util.Scanner;

public class GradesDriver {

    public static void main(String[] args) {

        Grades school = new Grades(90.9,87.9,99.9);

        Scanner in = new Scanner(System.in);
        System.out.println("Enter desired test number: ");
        int testnumber = in.nextInt();

        System.out.println(school);
        System.out.println("Exam score: " + school.getGrades(testnumber));
    }
}

package GradesClass;

public class Grades {
    private double num1, num2, num3;
    private int testnumber;
    private double average;

    public Grades(double num1, double num2, double num3) {
        num1 = 0;
        num2 = 0;
        num3 = 0;
    }
    public void setGrades(double scorenumber, int testnumber) {
        if (testnumber == 1) {
            num1 = scorenumber;
        } else if (testnumber == 2) {
            num2 = scorenumber;
        } else {
            num3 = scorenumber;
        }
    }
    public double getGrades(int testnumber) {
        if (testnumber == 1) {
            return(num1);
        } else if (testnumber == 2) {
            return(num2);
        } else {
            return(num3);
        }
    }
    public double average(double num1, double num2, double num3) {
        average = ((num1+num2+num3)/3.0);
        return(average);
    }
    public String toString() {
        return("Average: " + average);
    }
}

最佳答案

在成绩的构造函数中,将成员变量设置为零,而不是参数中提供的值。将构造函数更改为

public Grades(double num1, double num2, double num3) {
    this.num1 = num1;
    this.num2 = num2;
    this.num3 = num3;
}

关于java - 双重未在方法之间传递,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52676495/

10-09 06:11