简体   繁体   English

为什么我的 showAllUsers() 方法不使用每个对象的正确格式标题打印出用户列表?

[英]Why doesn't my showAllUsers() method print out the list of users with the correct formatted header for each object?

I have a program that that stores user objects into an array.我有一个将用户对象存储到数组中的程序。 There are two types of users (Customers, Employees) that both extend from user class.有两种类型的用户(客户、员工)都从用户类扩展而来。 When I run the method below in main it does not give the correct header format for each object.当我在 main 中运行下面的方法时,它没有为每个对象提供正确的标题格式。 Each extended class has its own unique header and share the getFormattedHeader() method.每个扩展类都有自己唯一的标头并共享 getFormattedHeader() 方法。 I thought that if i print out the array list that each time the object.getFormattedHeader() is called, it would give that objects specific header.我想,如果我打印出每次调用 object.getFormattedHeader() 时的数组列表,它会给出该对象特定的标题。 How can I go through the array and if it prints out a certain object, it prints out its unique header?我如何遍历数组,如果它打印出某个对象,它会打印出其唯一的标题?

public void showAllUsers() {
    System.out.println(hardwareStore.getAllUsersFormatted());
}

User.java用户.java

package hardwarestore;

import java.io.Serializable; import java.util.ArrayList;

public abstract class User implements Serializable {

    /**      *       */     private static final long serialVersionUID = 1L;

    private final int id;   private final String firstName;     private final String lastName;      public User(int id, String firstName, String lastName) {        this.id = id;       this.firstName = firstName;         this.lastName = lastName;   }       public abstract String getFormattedInfo(User user);     public abstract String getFormattedHeader();    public abstract ArrayList<Item> readDB(ArrayList<Item> items);

    public int getId() {        return id;  }

    public String getFirstName() {      return firstName;   }

    public String getLastName() {       return lastName;    }
         }

Employee.java雇员.java

package hardwarestore;

import java.util.ArrayList;

public class Employee extends User{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private final int socialNumber;
    private final float salary;

    public Employee(int id, String firstName, String lastName, int socialNumber, float salary) {
        super(id, firstName, lastName);
        this.socialNumber = socialNumber;
        this.salary = salary;
    }

    public int getSocialNumber() {
        return socialNumber;
    }

    public float getSalary() {
        return salary;
    }

    @Override
    public String getFormattedInfo(User user) {
        String text = String.format("| %-10s| %-25s| %-25s| %-20s| %-10s|%n", Integer.toString(user.getId()),
                user.getFirstName(), user.getLastName(),((Employee)user).getSocialNumber(),String.format("%.2f", ((Employee)user).getSalary()));
    text += " ------------------------------------------------------------------------------------\n";

    return text;
    }

    @Override
    public String getFormattedHeader() {
         String text = " ------------------------------------------------------------------------------------\n" +
                    String.format("| %-10s| %-25s| %-25s| %-20s| %-10s|%n", "ID Number", "First Name", "Last Name","Social Security", "Salary") +
                          " ------------------------------------------------------------------------------------\n";

         return text;
    }

    @Override
    public ArrayList<Item> readDB(ArrayList<Item> items) {
        // TODO Auto-generated method stub
        return null;
    }
}

Customer.java客户.java

package hardwarestore;

import java.util.ArrayList;

public class Customer extends User {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private final String phoneNumber;
    private final String address;


    public Customer(int id, String firstName, String lastName, String phoneNumber, String address) {
        super(id, firstName, lastName);
        this.phoneNumber = phoneNumber;
        this.address = address;
    }


    public String getPhoneNumber() {
        return phoneNumber;
    }


    public String getAddress() {
        return address;
    }


    @Override
    public String getFormattedInfo(User user) {
        String text = String.format("| %-10s| %-25s| %-25s| %-20s| %-10s|%n", Integer.toString(user.getId()),
                user.getFirstName(), user.getLastName(),((Customer)user).getPhoneNumber(), ((Customer)user).getAddress());
    text += " ------------------------------------------------------------------------------------\n";

    return text;
    }


    @Override
    public String getFormattedHeader() {
         String text = " ------------------------------------------------------------------------------------\n" +
                    String.format("| %-10s| %-25s| %-25s| %-20s| %-10s|%n", "ID Number", "First Name", "Last Name","Phone Number", "Address") +
                          " ------------------------------------------------------------------------------------\n";

         return text;
    }


    @Override
    public ArrayList<Item> readDB(ArrayList<Item> items) {
        // TODO Auto-generated method stub
        return null;
    }


}

Methods that suppose to list all users formatted by their customized formatting.假设列出按其自定义格式设置格式的所有用户的方法。

/**
     * method getAllUsersFormatted returns the current list of users in the 
     * Arraylist.
     * 
     * @return a formatted String representation of all the users in userList.
     */
    public String getAllUsersFormatted() {
        return getFormattedUserList(userList);
    }

    private String getFormattedUserList(ArrayList<User> users) {
        String text = users.get(0).getFormattedHeader();
        for(int i = 0; i<users.size(); i++) {
            text += users.get(i).getFormattedInfo(users.get(i));
        }
        return text;
    }

output:输出: 输出

The output gives the header for the employee and not the customer.输出给出了员工而不是客户的标题。

You can group the list of users according to their type and print the header only once for a type ( Customer or Employee )您可以根据用户的类型对用户列表进行分组,并且只为一种类型( CustomerEmployee )打印标题一次

List<User> list = ...
Map<Class<? extends User>, List<User>> groupedResult = list.stream()
        .collect(Collectors.groupingBy(e -> e.getClass()));
groupedResult
        .entrySet()
        .forEach(entry -> {
 //print the header for the object of the current class type
             entry.getValue()
                  .stream()
                  .findFirst()
                  .ifPresent(user -> user.getFormattedHeader());

           //print the data
            entry.getValue()
                 .forEach(user -> user.getFormattedInfo(user));
        });

Also, there is no need to send the user instance to getFormattedInfo as the method is called on the user object ( users.get(i).getFormattedInfo ) and you can access these instance variables directly You can change getFormattedInfo as此外,由于在用户对象( users.get(i).getFormattedInfo )上调用了该方法,因此无需将用户实例发送到getFormattedInfo并且您可以直接访问这些实例变量您可以将getFormattedInfo更改为

@Override
    public String getFormattedInfo(User user) {
        String text = String.format("| %-10s| %-25s| %-25s| %-20s| %-10s|%n", Integer.toString(getId()),
                getFirstName(), getLastName(), getPhoneNumber(), getAddress());
    text += " ------------------------------------------------------------------------------------\n";
    return text;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM