【发布时间】:2018-03-13 11:11:41
【问题描述】:
我尝试了很多方法来修复这个类,但没有奏效。我想创建一个酒店(数组)并检查并用另一个类中定义的人填充它,但我需要添加、删除、检查空项目并使用酒店类中的方法返回它们的索引。问题是当我在一个方法中更改数组时,我无法返回更改后的值,当我尝试添加其他类成员试图解决它时,我以 indexOutOfboundryException 结束。请您看一下代码并告诉我您是否看到错误,为什么我无法返回更改后的值以及为什么我的索引越界
非常感谢!
package com.company;
public class Hotel1 {
private int numberOfRooms1; // Number of rooms
private Person[]bookingList1=new Person[numberOfRooms1];// booking list with initial length of the number of rooms
private int uniqueId1;
private Person person1;
private int currentIndex;
private boolean isEmpty=true;
public int getNumberOfRooms1() {
return numberOfRooms1;
}
private Ticket ticket1;
public Hotel1(int numberOfRoomss1) {// The constructor has one attribute which is the number of the rooms
this.numberOfRooms1 = numberOfRoomss1;
}
//check in method
public Boolean isEmpty(){
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
if (!bookingList1[currentIndex].equals(null))
isEmpty=false;
else isEmpty= true;
}
return isEmpty;
}
public int findEmptyRooms(){
if (isEmpty)
{
for (currentIndex=0;currentIndex<bookingList1.length;currentIndex++){
return currentIndex;
}
return currentIndex;
}
return currentIndex;
}
public Person checkIn1(Person person){
if (isEmpty==true){
return bookingList1[findEmptyRooms()]=person;
}
else {
System.out.println("There is no empty rooms");
return null;
}
}
}
【问题讨论】:
-
提示:删除所有不需要的实例变量
-
其他方法需要所有实例。唯一的问题是当我尝试从 main 方法测试方法时,我无法使用这些方法更改数组
-
不,他们不是。您正在滥用实例变量以不声明本地变量(恕我直言)。
-
没有。并非所有实例变量都是必需的。例如,您根本不应该将变量
private boolean isEmpty作为字段。如果你想知道是否有空房间,你应该使用方法 isEmpty 而不是一些甚至可能不是最新的状态变量。此外,您的大多数方法都没有考虑根本没有房间(大小为 0 的数组)的情况,这可能会导致错误。
标签: java arrays methods return