java - 如何打印数组的特定部分?

标签 java

我的代码中存在一个小错误,需要帮助。我有一个程序,有 4 个 String 数组,我必须使用构造函数将它们组合并在不同的位置打印。我需要编写一个方法:Employee[] searchWithId(Employee[] list, String search),它在数组中搜索字符串并返回匹配的string以及其他相应信息。

例如:

searchWithId(列表, "P102432");//在列表中搜索给定的 id

输出:

Searching for the id number:P102432 ...
Found the record for the id number:P102432

first name:Amber    Last Name:Nogofski
Id number:P102432
Employee number:No employee number has been assigned yet!

这是我到目前为止的代码:

员工类别:

public static class Employee {

    private String firstName;
    private String lastName;
    private String idNumber;
    private String employeeNumber;
    private int employeeCount;

    /**
     * Constructor
     *
     * @param firstName first name
     * @param lastName last name
     * @param idNumber id number
     */
    public Employee(String firstName, String lastName, String idNumber) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.idNumber = idNumber;
        employeeCount = 0;
    }

    /**
     * Accessors here
     */
    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getIdNumber() {
        return idNumber;
    }

    public String getEmployeeNumber() {
        return employeeNumber;
    }

    // mutators here
    /**
     * @param firstName first name
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     * @param lastName last name
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @param idNumber id number
     */
    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    /**
     * @param employeeNumber employee number
     */
    public void setEmployeeNumber(String employeeNumber) {
        this.employeeNumber = "";
    }

    @Override
    public String toString() {
        String result = "First name: " + getFirstName() + "\nLast name: " + getLastName()
                + "\nId number: " + getIdNumber() + "\nEmployee number: ";
        if (getEmployeeNumber() == null) {
            return result + "No employee number has been assigned yet!\n";
        }
        return result + getEmployeeNumber() + "\n";
    }

}

我的主要方法和其他方法:

public static void main(String[] args) {
    String[] firstNames = {"Fred", "John", "Amir", "James", "Bob", "Jay", "Amber"};
    String[] lastNames = {"Bond", "Kates", "Memar", "White", "Marley", "Brown", "Nogofski"};
    String[] idNumbers = {"R111111", "A222222", "AB11111", "KR22121", "V311133", "L242434", "P102432"};
    String[] employeeNum = {"1111", "2222", "3333", "4444", "5555", "6666", "7777"};

    Employee[] list = new Employee[firstNames.length];
    list = listOfEmployees(firstNames, lastNames, idNumbers); // create the list of employees in one array    
    System.out.println("List of employees before sorting...\n");
    printEmployeeList(list); //print the list of employees

    System.out.println(); // new line
    searchWithId(list, "P102432"); // search the list for the given id
    searchWithLastName(list, "Bond"); // search the list for the given last name

    System.out.println(); // new line
    searchWithId(list, "P1024444"); // search the list for the given id
    searchWithLastName(list, "BoNd"); // search the list for the given last name

    System.out.println();// new line
    sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
    list = assignEmployeeNum(list, employeeNum); // assign the employee number to the employees

    System.out.println("+++After adding the employee number to the list+++");// new line
    printEmployeeList(list); // print the list again with the employee number

    searchWithEmployeeNum(list, "5555"); // search the list for the given employee number 
    sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
}

public static Employee[] listOfEmployees(String[] firstName, String[] lastName, String[] idNumber) {
    Employee[] list = new Employee[firstName.length];
    for (int i = 0; i < list.length; i++) {
        list[i] = new Employee(firstName[i], lastName[i], idNumber[i]);
    }
    return list;
}

public static void printEmployeeList(Employee[] list) {
    Arrays.stream(list).forEach(System.out::println);
}

public static Employee[] searchWithId(Employee[] list, String search) {
    System.out.println("Searching for the id number: " + search);
    for (int i = 0; i < list.length; i++) {
        if (list[i].getIdNumber().equals(search)) {
            System.out.println("Found id number: " + search);
            //Arrays.toString(list); <- my try
        }
    }
    return list;
}

最佳答案

您可以按如下方式进行:

import java.util.Arrays;

public static Employee[] searchWithId(Employee[] list, String search) {
   System.out.println("Searching for the id number: " + search);            
   Employee[] filteredEmployees = new Employee[list.length];
   int index = 0;
   for (int i = 0; i < list.length; i++) {
      if (list[i].getIdNumber().equalsIgnoreCase(search)) {
         filteredEmployees[index++] = list[i];
      }
   }
   // It'll remove the null values:
   return Arrays.copyOfRange(filteredEmployees, 0, index);
}

Java 8 版本:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

public static Employee[] searchWithId(Employee[] list, String search) {
   System.out.println("Searching for the id number: " + search);
   return Arrays.asList(list)
            .stream()
            .filter(e -> e.idNumber.equalsIgnoreCase(search))
            .collect(Collectors.toList())
            .toArray(new Employee[list.length]);
}

关于java - 如何打印数组的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38278270/

相关文章:

java - 解决maven项目中的多个SLF4J绑定(bind)

java - 在声明中赋值还是在构造函数中赋值?

java - 集成 JS 和 Java

java - 在 java 类中处理 JSP (Spring MVC)

java - 从字节数组 java 创建 BufferedImage

java - Javafx 未触发组鼠标事件

Java MySql 通讯链路失败

java - Java中的类加载时间

java - 无限循环线程中的问题

java - 可以批量sql查询吗?