-3

我有一个 get/set 程序,我试图获得平均结果,但我总是得到 0.0。

  • 该程序有 5 个实例,每个实例有 1 个返回方法
  • 主要有 2 个用户输入和 3 个年级数字

账户类:

public class Account {
    private String name1;
    private String name2;
    private double grade1;
    private double grade2;
    private double grade3;
    private double average;

    public Account(String a1, String a2, double b1, double b2, double b3) {
        name1 = a1;
        name2 = a2;
        grade1 = b1;
        grade2 = b2;
        grade3 = b3;
    }

    public void setName1(String a1) {
        name1 = a1;
    }

    public void setName2(String a2) {
        name2 = a2;
    }

    public void setGread1(double b1) {
        grade1 = b1;
    }

    public void setGread2(double b2) {
        grade2 = b2;
    }

    public void setGread3(double b3) {
        grade3 = b3;
    }

    public String getName1() {
        return name1;
    }

    public String getName2() {
        return name2;
    }

    public double getgrade1() {
        return grade1;
    }

    public double getgrade2() {
        return grade2;
    }

    public double getgrade3() {
        return grade3;
    }

    public void setAverage(double ave) {
        average = ave;
    }

    public double getAverage() {
        return average = (grade1 + grade2 + grade3) / 3;
    }

    public String toString() {
        return String.format("%-5s %2s the average is: %5s%% ", name1, name2,
                average);
    }
}

主要方法:

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

    System.out.println("Enter the  frist  and last name of student" );

    String inf=in.nextLine();
    String infs=in.nextLine();

    Account account= new Account(inf,infs,5,6,7);    
    System.out.print(account);
}

我厌倦了试图解决它,所以请帮助我。

4

2 回答 2

0

您从不分配任何值,average因此它保持其默认值0.0. 将此作业从getAverage

average = (grade1 + grade2 + grade3) / 3;

给你的构造函数。Getter 和 setter 通常不包含这种类型的逻辑。

于 2013-01-26T11:48:57.883 回答
0

如果您已经在构造函数中完成了初始化,那么getter 和 setter有什么用。

任何方式,你的公众 Account(String a1 ,String a2 ,double b1,double b2,double b3)

应该是这样的:

public  Account(String a1 ,String a2 ,double b1,double b2,double b3) {

name1=a1;
name2=a2;
grade1=b1;
grade2=b2;
grade3=b3;
average=getAverage();

}

正如@Reimeus 所建议的那样,您永远不会为average.

于 2013-01-26T12:19:58.900 回答