Get,Set)无法获得平均结果

时间:2013-01-26 11:39:58

标签: java

我有一个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);
}

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

2 个答案:

答案 0 :(得分:0)

您永远不会任何值分配给average,因此它会保留默认值0.0。从getAverage

移动此作业
average = (grade1 + grade2 + grade3) / 3;

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

答案 1 :(得分:0)

如果您已经在构造函数中进行了初始化,那么getters and setters的用途是什么。

任何方式,您的公众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分配任何值。