【问题标题】:Adding values from a text file using a for loop?使用 for 循环从文本文件中添加值?
【发布时间】:2018-04-18 18:31:10
【问题描述】:

所以我正在处理两个类和一个文本文件。在我的主要工作中,我有我所有的获取者和设置者,但我试图找到工资的总和,但我无法弄清楚。到目前为止,这是我所拥有的:

private static void printStats(Worker[] people, int count) {

    double total = 0.0;

    for (int i = 0; i< count; i++) 
        total += people[i];
}

我不知道我做错了什么。另外,我刚刚开始,所以我没有很好地掌握这个概念,我真的迷路了。 :-/

这是我的 Worker 类:

公共类工人{

private String first;
private String last;
private int total_hrs;
private double pay;

public Worker(String last, String first, int total_hrs, double pay) {

    this.first = first;
    this.last = last;
    this.total_hrs = total_hrs;
    this.pay = pay;

}

public void setFirst(String first) {

    this.first = first;

}

public void setLast(String last) {

    this.last = last;

}

public void setTotal_hrs(int total_hrs) {

    this.total_hrs = total_hrs;

}

public void setPay(double pay) {

    this.pay = pay;

}

public String getFirst() {

    return first;

}

public String getLast() {

    return last;

}

public int getTotal_hrs() {

    return total_hrs;

}

public double getPay() {

    return pay;

}

【问题讨论】:

  • 请发布工人阶级
  • 您只能对 int/double/float 等数字类型进行求和,而不能对 Worker 等任意用户定义类型求和。您需要调用 Worker 实例的 getter 来检索要求和的数字,即 total += people[i].get&lt;SomeThing&gt;()
  • total += people[i].getPay()
  • 如果您的代码显示错误,请在此处发布。

标签: java arrays for-loop add


【解决方案1】:
private static void printStats(Worker[] people, int count) {

    double total = 0.0;

    for (int i = 0; i< count; i++) 
        total += people[i].getTotal_hrs();
}

调用people[i] 只是访问Worker 对象。获得对象后,您需要调用 getTotal_hrs() 以获取数组中索引 i 处工作人员的工作时间。或 getPay() 或任何你想要求和的东西,但它必须是 double、int 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-31
    • 2011-10-27
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    相关资源
    最近更新 更多