gpt4 book ai didi

java - Double 没有从一个方法传递到另一个方法

转载 作者:行者123 更新时间:2023-12-01 17:48:42 25 4
gpt4 key购买 nike

我设计了一个小程序,其中有三个考试成绩,我使用 Grades 类来计算三个考试成绩的平均值。另外,我提示输入考试编号(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);
}
}

最佳答案

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

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

关于java - Double 没有从一个方法传递到另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52676495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com