java - 从主类中的另一个类访问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());
}
}
解决方案
换行
isBookingList = new Booking(null, null, null).getBookingList();
和
isBookingList = new TimeSlot("your sn").getBookingList();
现在试试你的 for 循环。
推荐阅读
- reactjs - React Redux:调度时的无限循环
- javascript - 在数组中获取值的问题 - XMLHttpRequest
- asp.net-mvc - 如何将 3 个模型数据传递到 asp.net MVC 视图
- python - 如何跟踪 pandas 中不同类型的缺失值?
- php - WP 插件外部 API,自定义帖子类型
- json - Swift 4 JSON 解码
- java - Spring boot - 添加 JSTL 依赖会导致问题
- r - 根据测量日期与另一个数据集中的其他两个日期相比,标记一个数据集中的行
- javascript - 调用自身的阶乘函数
- javascript - RegExp,如何在 javascript 中连接字符串以创建动态正则表达式?