【问题标题】:Using indexOf() method for ArrayList of objects对对象的 ArrayList 使用 indexOf() 方法
【发布时间】:2021-09-25 20:59:11
【问题描述】:

在我的程序中,我有一个供应商类和一个医院类,并将这些类的实例存储在称为供应商和医院的数组列表中。我的 Vendor 类有一个字符串数组,其中包含与 Hospital 类的实例相对应的医院名称。我试图找到一种方法,从属于 Vendor 类的字符串数组中的医院名称,到为医院数组列表获取该医院的索引值。抱歉,如果这篇文章没有多大意义,我对编码很陌生。任何帮助将不胜感激。

编辑:请使用以下 Ctrl+F 跳转到有问题的特定代码行

//检查是否住院

供应商类别

package com.company;
import java.util.Arrays;
import java.util.Scanner;

public class Vendor {

    //static variables are the same for all vendor instances
    static int numOfHospitals;
    static int numOfAppointments;

    //non-static variables are specific to one vendor instance
    int priorityNum;
    String salespersonName;
    String vendorCompanyName;
    String [] vendorPicks;
    String[] vendorSchedule;

    public void printVendorSchedule() {
        System.out.println(Arrays.toString(vendorSchedule));
    }

    public void printVendorPicks () {
        System.out.println(Arrays.toString(vendorPicks));
    }

    public String getVendorSchedule (int appointmentSlot) {
        return vendorSchedule [appointmentSlot];
    }

    public String getVendorPick (int currentHospitalPick) {
        return vendorPicks[currentHospitalPick];
    }

    public boolean checkVendorSchedule (int appointmentSlot) {
        return ((vendorSchedule[appointmentSlot]).equals("open"));
    }

    public void setVendorAppointment (int appointmentSlot, String hospitalName) {
        vendorSchedule[appointmentSlot] = hospitalName;
    }

    public Vendor createNewVendor(int priorityNum, int numOfAppointments, int numOfHospitals, String salespersonName, String vendorCompanyName){
        this.priorityNum=priorityNum;
        this.salespersonName=salespersonName;
        this.vendorCompanyName=vendorCompanyName;
        this.vendorPicks = new String[numOfHospitals];
        this.vendorSchedule = new String[numOfAppointments];
        for (int i = 0; i <numOfAppointments; i++) {
            this.vendorSchedule[i] = "open";
        }
        Scanner input = new Scanner(System.in);
        Vendor vendorToAdd = new Vendor();

        //loop to add vendor's hospital picks
        int counter = 0;
        while (counter < numOfHospitals) {
            System.out.println("Enter the #" +(counter+1) +" hospital for "+salespersonName+". If there are no more hospitals for this vendor, enter Done.");
            String placeHolder = input.nextLine();
            if (placeHolder.equalsIgnoreCase("done")) {
                break;
            }
            vendorPicks[counter]=placeHolder;
            counter++;


        }
        return vendorToAdd;
    }
}

医院类

package com.company;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;

public class Hospital {

    //static variables here
    int numOfAppointments;
    int numOfHospitals;
    //non-static variables here
   String nameHospital;
   String nameDirector;
   String [] hospitalSchedule;

   public void printHospitalSchedule () {
       System.out.println(Arrays.toString(hospitalSchedule));
   }

   public String getHospitalSchedule(int appointmentSlot) {
       return hospitalSchedule[appointmentSlot];
   }

    public boolean checkHospitalSchedule (int appointmentSlot) {
        return ((hospitalSchedule[appointmentSlot]).equals("open"));
    }

    public void setHospitalAppointment (int appointmentSlot, String nameVendor) {
       hospitalSchedule[appointmentSlot] = nameVendor;
    }


    public Hospital createNewHospital(int numOfAppointments, int numOfHospitals,
                                       String nameHospital, String nameDirector) {
        Hospital h1 = new Hospital();
        this.nameDirector=nameDirector;
        this.nameHospital=nameHospital;
        this.hospitalSchedule = new String[numOfAppointments];
        for (int i=0; i < numOfAppointments; i++) {
            hospitalSchedule[i] = "open";
        }
        return h1;
    }
}

主类

package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;

public class Main {



    public static void main(String[] args) {

        // Inputting #vendors, #hospitals
        int vendorCounter=1;
        System.out.println("Enter the total number of appointment slots.");
        Scanner myScanner = new Scanner(System.in);
        int numOfAppointments = Integer.parseInt(myScanner.nextLine());
        System.out.println("Enter the total number of hospitals in the draft.");
        int numOfHospitals = Integer.parseInt(myScanner.nextLine());
        ArrayList<Hospital> hospitals = new ArrayList<Hospital>();

        //creating hospitals
        int hospitalCounter = 1;
        while (hospitalCounter <=numOfHospitals) {
            System.out.println("Enter the name of hospital #" + hospitalCounter);
            String currentHospitalName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
            System.out.println("Enter the director's name for " + currentHospitalName + ".");
            String currentDirectorName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
            Hospital h1 = new Hospital();
            h1.createNewHospital(numOfAppointments, numOfHospitals, currentHospitalName, currentDirectorName);
            hospitals.add(h1);
            hospitalCounter++;
        }

        //creating vendors
        ArrayList<Vendor> vendors = new ArrayList<Vendor>();
        Scanner myInput = new Scanner(System.in);
        while (vendorCounter != 2000){
            System.out.println("Are you entering a new vendor? Enter Yes or No");
            String isAddingNewVendor;
            isAddingNewVendor= myScanner.nextLine();
            if (isAddingNewVendor.equalsIgnoreCase("yes"))
            {
                System.out.println("Enter the name of the salesperson.");
                String salespersonName = myInput.nextLine();
                System.out.println("Enter the company name for "+salespersonName+".");
                String vendorCompanyName = myInput.nextLine();
                Vendor v1 = new Vendor();
                v1.createNewVendor(vendorCounter, numOfAppointments, numOfHospitals,salespersonName,vendorCompanyName);
                vendors.add(v1);
                vendorCounter++;
            }
            else vendorCounter = 2000;



        }
       /* System.out.println(vendors.get(0).vendorCompanyName);
       System.out.println(hospitals.get(0).nameHospital);
       System.out.println(vendors.get(0));
       vendors.get(0).printVendorSchedule();
       vendors.get(0).printVendorPicks();
       hospitals.get(0).printHospitalSchedule();
      if (vendors.get(0).checkVendorSchedule(0)) {
          System.out.println ("This appointment slot is open for the vendor.");
        }
      if (hospitals.get(0).checkHospitalSchedule(0)) {
          System.out.println("This appointment slot is open for the hospital.");
      }*/

        for (int i = 0; i < numOfHospitals; i++) {
            System.out.println("Information for hospital #" + i);
            System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
            System.out.println("Director's name: " + hospitals.get(i).nameDirector);
            System.out.println("The hospital's initial schedule:");
            hospitals.get(i).printHospitalSchedule();
        }

        for (int i = 0; i < vendors.size(); i++) {
            System.out.println("Information for vendor #" + i);
            System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
            System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
            System.out.println("The vendor's hospital choices:");
            vendors.get(i).printVendorPicks();
            System.out.println("The vendor's initial schedule:");
            vendors.get(i).printVendorSchedule();
        }


        //draft loop logic
        int draftRound = 1;
        while (draftRound <= numOfAppointments) {
            if (draftRound % 2 == 1) {
                //insert code for odd-numbered draft rounds here.
                //these rounds should start with picker 1, then 2, 3, etc.

                int currentVendor = 0;        //starts this round with the first vendor
                while (currentVendor < vendors.size()){
                    //this while loop continues running through a single draft round until all vendors get a pick
                    int currentAppointmentSlot = 0;
                    int currentVendorPickSlot=0;
                    while (currentVendorPickSlot < numOfHospitals) {      //this loops through a single vendor until all appointments checked or appt assigned
                        //check if hospital and vendor are both open
                        String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
                        System.out.println(currentHospital);
                        int currentHospitalsIndex = hospitals.indexOf(currentHospital);  //indexof is returning -1 creating the exceptionoutofbounds
                        System.out.println("Current hospital index:"+ currentHospitalsIndex);
                        if ( hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
                            currentAppointmentSlot++;

                        }
                        else {
                            vendors.get(currentVendor).setVendorAppointment(currentVendorPickSlot, hospitals.get(currentHospitalsIndex).nameHospital);
                            hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentVendorPickSlot, vendors.get(currentVendor).salespersonName);
                            break;   // does this break the loop?
                        }
                    }

                    currentVendor++;
                }

                draftRound++;


            }
            if (draftRound % 2 == 0) {
                //insert code for even-numbered draft rounds here.
                //these rounds should start with the last picker and go down by 1 each turn until 1st picker.
                int currentVendor = vendors.size()-1;       //starts this draft round with the last vendor
                while (currentVendor >= 0) {
                    //this while loop continues running through a single draft round until all vendors get a pick
                    int currentAppointmentSlot = 0;                   //looping through the hospital choices for a single vendor
                    int currentVendorPickSlot=0;
                    while (currentVendorPickSlot < numOfHospitals) {
                        //check if hospital and vendor are both open
                        String currentHospital =  vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
                        int currentHospitalsIndex = hospitals.indexOf(currentHospital);
                        if (hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
                            currentAppointmentSlot++;
                            //continuing the loop if the appointment slot doesn't work
                        }
                        else {
                            vendors.get(currentVendor).setVendorAppointment(currentAppointmentSlot, hospitals.get(currentHospitalsIndex).nameHospital);
                            hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentAppointmentSlot, vendors.get(currentVendor).salespersonName);
                            currentVendor++;
                            break;   // does this break the loop?
                        }
                    }

                    currentVendor++;
                }

            draftRound++;
            }
            else break;

        }

        for (int i = 0; i < numOfHospitals; i++) {
            System.out.println("Information for hospital #" + i);
            System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
            System.out.println("Director's name: " + hospitals.get(i).nameDirector);
            System.out.println("The hospital's final schedule:");
            hospitals.get(i).printHospitalSchedule();
        }

        for (int i = 0; i < vendors.size(); i++) {
            System.out.println("Information for vendor #" + i);
            System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
            System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
            System.out.println("The vendor's final schedule:");
            vendors.get(i).printVendorSchedule();
        }

    }}

【问题讨论】:

  • indexOf 使用类的 .equals() 方法标识对象。如果你不覆盖它,它将使用超类 Object 的 .equals ,只要它不是同一个实例,它就不会找到它。您可能想要覆盖列表中类的 .equals() 和 .hashCode() 方法(IDE 提供了代码生成,但如果需要,您可以自定义它)。
  • @MRS 我可以使用 java 8 流 API 为您提供答案
  • @Matteo NNZ 非常感谢您的回复!你愿意为我提供一个例子吗?如果不是,我理解并非常感谢您的回复。
  • @navnath 非常感谢您的回复。我将不胜感激任何帮助。我不确定我是否理解使用 java 8 流 API 提供答案的重要性,但如果您愿意向我解释,任何帮助将不胜感激。

标签: java indexof


【解决方案1】:

首先使用流,我们将遍历医院列表,

从列表中找出名称等于currentHospital名称的医院,使用findFirst取出第一个结果。

由于结果可能可用也可能不可用,因此它返回 Optional。 所以在 Optional 上,我们会说如果它(我们正在寻找的医院对象)存在,我们将使用 get 方法将医院从它中取出

Optional<Hospital> result = hospitals.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();

if(result.isPresent()){
    Hospital hospital = result.get();
}

【讨论】:

  • 如果我杀了这个,请原谅我。这是它应该适应的方式吗? ``` 字符串 currentHospital = vendor.get(currentVendor).vendorPicks[currentVendorPickSlot];可选 结果 = hospital.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();医院 tempHospital = null; if (result.isPresent()) { tempHospital = result.get(); } ```
  • 这里有问题int currentHospitalsIndex = hospitals.indexOf(currentHospital); System.out.println("Current hospital index:"+ currentHospitalsIndex); if ( hospitals.get(currentHospitalsIndex) 对吧?
  • 如果我们在帖子中讨论我的原始代码,问题是下面的代码会返回 -1,所以它什么也没找到: int currentHospitalsIndex = hospital.indexOf(currentHospital) ;我在上面的评论中尝试了其他代码,我认为它将 tempHospital 视为字符串而不是对象。
  • 目前您在hospitals 中有值吗?
  • Lol 对不起,我把可选的 而不是可选的 。错误消息现在消失了。
猜你喜欢
  • 2011-02-15
  • 2018-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
  • 2017-06-26
相关资源
最近更新 更多