首页 > 解决方案 > 从主类中的另一个类访问arraylist

问题描述

我不知道如何制作这个,因为我是 java 新手。我想将我的 TimeSlot 类的数组列表中的所有对象显示到主类中。我尝试了几种方法,例如使用 for (int = 0; i < bookingList.size(); i++) 但仍然无法工作。我得到 nullPointerException 所以我不知道是否有其他方法可以解决这个问题。请帮忙。

时隙.java

import java.util.ArrayList;

public class TimeSlot {

    private String slotName;
    private ArrayList<Booking> bookingList;


    public TimeSlot(String sn) {

        this.slotName = sn;
        this.bookingList = new ArrayList<Booking>();

        Booking booking1 = new Booking("CS1011", "A04", "Aiman");
        Booking booking2 = new Booking("CS1012", "A13", "Nazim");
        Booking booking3 = new Booking("CS1013", "A06", "Sarah");
        Booking booking4 = new Booking("CS1014", "A21", "Majid");

        bookingList.add(booking1);
        bookingList.add(booking2);
        bookingList.add(booking3);
        bookingList.add(booking4);



    }

    public String getSlotName() {
        return slotName;
    }

    public ArrayList<Booking> getBookingList() {
        return bookingList;
    }

    public boolean isBooking (String bId, String cId, String sId) {
        boolean isVerifyBooking = false;
        for(Booking newBooking: bookingList){
            if((newBooking.getBookingId().equals(bId)) && newBooking.getComputerId().equals(cId) && newBooking.getStudentId().equals(sId)) {
                return true;
            }
        }
            return isVerifyBooking;
    }

}

主.java

public static void main(String[] args) {

        // TODO Auto-generated method stub
        Faculty faculty = new Faculty("Computer Science and Technology", "");
        Lab lab = new Lab("");
        ArrayList<Computer> computerList = new ArrayList<Computer>();
        ArrayList<Booking> isBookingList = new Booking(null, null, null).getBookingList();

           if (option.equals("1")) {

             System.out.println("\nChoose day: ");
             String days = sc.next();
             System.out.println("\nChoose date: ");
             String date = sc.next();

             boolean isValidDay = lab.verifyDate(days, date);

             if (isValidDay) {
               Day day = new Day(days, date);
               System.out.println("\nBooking date: " + day.getDay() + " " + day.getDate());
               System.out.println("\nPlease select a computer (A01 ~ A40): ");
               String cId = sc.next();

              System.out.println(isBookingList.size());
            }
          } else if (option.equals("2")) {

          // I want to display it here

          for (Booking booking: isBookingList) {
            System.out.println(booking.getBookingList());
         }
      }

标签: java

解决方案


换行

isBookingList = new Booking(null, null, null).getBookingList();

isBookingList = new TimeSlot("your sn").getBookingList();

现在试试你的 for 循环。


推荐阅读