【问题标题】:How do you add a single parameter of an object with multiple parameters to a string from an arraylist of that object?如何将具有多个参数的对象的单个参数添加到该对象的数组列表中的字符串?
【发布时间】:2016-03-15 09:44:46
【问题描述】:

我正在尝试重写 toString() 以打印名称。我使用对象员工数组列表中每个员工的 getNm() 。员工有参数(工资、nm、工作时间、加班时间)
我已将我关注的代码加粗。

public class Main {
    public static void main(String[] args){
        workers workerlist = new workers();
        workerlist.setNumberEmployees();
        workerlist.instantiateEmployees();
        System.out.println(workerlist.toString());
    }
}

public class Employees extends workers{
    public double pay;
    public String nm;
    public double hours;
    public double overtime;

    public Employees(double pay, String nm, double hoursWorked, double overtimeHours){
    }

        public double getPay(){
            return pay;
        }

        public void setPay(double pay){
        }

        public String getNm(){
            return nm;
        }

        public void setNm(String nm){
        }

        public double getHours(){
            return hours;
        }

        public void setHours(double hours){
        }

        public double getOvertime(){
            return overtime;
        }

        public void setOvertime(double overtime){
        }

    }

  import java.util.ArrayList;
import java.util.Scanner;

public class workers{
    public int employeenumber;
    public String nm;
    ArrayList<Employees> workerList = new ArrayList<Employees>();
    Scanner input = new Scanner(System.in);

    public void setNumberEmployees(){
        System.out.println("How many employees do you have?");
        employeenumber = input.nextInt();
    }

    public int getNumberEmployees(){
        return employeenumber;
    }

    public void instantiateEmployees(){
        for(int i=1; i<=employeenumber; i++){
            workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
        }
    }


    public String toString(){
        String st = "";
        for(int i=0; i<employeenumber; i++){
            **st += workerList.toString();**
// ".toString() is there to test the setting of parameters, I am interested in replacing this part.
        }

        return st;
    }

}

预期输出 [员工 1 的姓名,员工 2 的姓名,...员工 n 的姓名]

【问题讨论】:

  • “测试参数设置”是什么意思?
  • 查看 Object Employee 是否接受变量的实例化。因此,当我使用 workerList.toString() 运行时,它将为每个员工编号打印 [ , , , ,] @Maljam
  • 你能添加你的预期输出吗?

标签: java eclipse string arraylist tostring


【解决方案1】:

我认为下面的代码会给出你预期的结果。

public class Main {
    public static void main(String[] args) {
        workers workerlist = new workers();
        workerlist.setNumberEmployees();
        workerlist.instantiateEmployees();
        System.out.println(workerlist.toString()); //call toString to take workerlist
    }
}

重写Employees toString方法,不要忘记在构造函数中更新nm参数

public class Employees extends workers {
    public double pay;
    public String nm;
    public double hours;
    public double overtime;

    public Employees(double pay, String nm, double hoursWorked, double overtimeHours) {
        this.nm = nm; //do not forget set value
    }

    public double getPay() {
        return pay;
    }

    public void setPay(double pay) {
    }

    public String getNm() {
        return nm;
    }

    public void setNm(String nm) {
    }

    public double getHours() {
        return hours;
    }

    public void setHours(double hours) {
    }

    public double getOvertime() {
        return overtime;
    }

    public void setOvertime(double overtime) {
    }

    @Override
    public String toString() {
        return getNm(); //Employees toString method will return nm
    }

}

重写toString方法并调用arraylist的toString方法。

public class workers {
    public int employeenumber;
    public String nm;
    ArrayList<Employees> workerList = new ArrayList<Employees>();
    Scanner input = new Scanner(System.in);

    public void setNumberEmployees() {
        System.out.println("How many employees do you have?");
        employeenumber = input.nextInt();
    }

    public int getNumberEmployees() {
        return employeenumber;
    }

    public void instantiateEmployees() {
        for (int i = 1; i <= employeenumber; i++) {
            workerList.add(new Employees(0.0, "nm", 0.0, 0.0));
        }
    }

    public String toString() {
        return workerList.toString(); //no need to iterate on arraylist, Arraylist.toString method will call each Employees toString method.
    }
}

【讨论】:

    【解决方案2】:

    Yusuf K. 和 Andrew Tobilko 已正确回答您的问题。只是给你一些提示来改进你的课程:

    • 为什么你叫Employees,即使你的类可以代表一个雇员;所以我会改为 Employee
    • 为什么要定义两次 nm 字段?它在 Employees 类派生的 Workers 类中声明。
    • setNumberEmployees() 方法不符合 JavaBeans 约定;它必须声明为

      public void setNumberEmployees(final String noEmployees) {
          employeenumber = noEmployees;
      }
      

      并且对 setNumberEmployees() 的调用应该在 ma​​in() 方法中作为

      public static void main(String[] args){
          workers workerlist = new workers();
          Scanner input = new Scanner(System.in);
          workerlist.setNumberEmployees(input.nextInt());
          workerlist.instantiateEmployees();
          System.out.println(workerlist.toString());
      }
      
    • 最后,您说的是参数。它们实际上称为字段实例变量

    【讨论】:

    • 我一定会调查你确实列出了优点。这就是我喜欢称之为我的废品计划。我倾向于制作一个草率的版本,然后一旦一切正常,我看看它是否有效,没有错误或跳过一些东西,如果可能的话,我想制作一个新的作为最终产品。但我肯定会把这些作为要回顾的一些要点。有时一个程序真的只需要一个全新的写作,这可能就是其中之一。
    • @ujulu 我对你的唯一论据是这个。即使在客户端,错误也会经常声明构造函数的参数。 IE。如果我尝试调用一个空的构造函数Employee A = new Employee();,Eclipse 将给出错误和解决方案Change constructor "Employee(double, string, double, double)": remove parameters double, string, double, double。那么调用这些参数我怎么错了?实例变量不会像 private String nm; 那样简单,而字段不会像 private final int x = 0; 这样简单吗?如果我错了,请纠正我。
    • 对我来说,对构造函数和方法使用术语 parameter 是正确的。并且instance variablefield没有区别;例如:在 public Employee(final String name) {} (应该是构造函数) name 被称为 formal parameter 或者你只需将其称为构造函数的参数;但是当你在类级别声明一个变量时,它是实例变量或字段,除非该变量声明包含关键字static,在这种情况下它被称为类变量或静态变量.
    【解决方案3】:
    public String toString(){
        String st = "";
        for(int i=0; i < employeenumber; i++)
            st += workerList.get(i).toString();
    
        return st;
    }
    

    但是这个解决方案并不是最好的。我建议你下一个:

    public String toString(){
        StringBuilder builder = new StringBuilder();
        workerList.stream().map(Employees::toString).forEach(builder::append);
    
        return builder.toString();
    }
    

    当然,您必须在 Employees 类中覆盖 toString()。例如,

    @Override public String toString() {
        return new StringJoiner(", ")
                    .add(Double.toString(pay))
                    .add(nm)
                    .add(Double.toString(hours))
                    .add(Double.toString(overtime))
                .toString();
    }
    

    【讨论】:

    • 您为什么建议第二种解决方案?是不是更有效率?它有什么解决方案没有做的?
    • @Adamc23,当我们谈论字符串连接时,通常我们使用StringBuilder/StringBuffer(如果我们使用多线程)以获得更好的性能。
    • @Amamc23,编译器可能会将第一个构造优化为第二个。
    • 进一步阅读,似乎StringBuilder / StringBuffer 附加了已经存在的字符串。基于此,最好为列表中的所有对象创建一个主要的StringBuilder,还是为每个对象创建一个单独的StringBuilder
    • @Adamc23,一应俱全
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多