控制台版 - 酒店管理系统
欢迎进入信息大酒店
搭建酒店框架 -> 确定酒店有多少层,每层有多少个房间 例如:有5层,每层有5个房间
该系统主要功能如下: 1.查房(show) 1001 1002 1003 1004 1005 null null null null null 2001 2002 2003 2004 2005 null null rose null null 3001 3002 3003 3004 3005 null null null null null 4001 4002 4003 4004 4005 null null null null null 5001 5002 5003 5004 5005
2.办理入住(in) 3.办理退房(out) 4.退出程序(exit) ps:按0,退出程序
问题1:面向对象创建的方式没有很深的理解
public class Room {
int num; //房间号
Guest guest; //有人: 显示人名 没人: null
public Room(int num) {
this.num = num;
}
}
class room{
int number;
String condition;//状态
room[] rooms = new room[20];//房间数量
//初始化房间
room(int number,String condition) {
this.number = number;
this.condition = condition;
}
room(String condition){}
room(int number){}
void ww(){
int count = 0;
for (int i = 0; i < 20; i++) {
rooms[i] = new room(i,null);
System.out.print(rooms[i]+"\t");
count ++;
/* if (count % 5 == 0){
System.out.println();
}*/
}
}
room(){}
@Override
public String toString() {
return number + "\t"+condition;
}
}
对比发现其中的问题是:创建的房间数量并不属于room的成员属性,我们讨论的应该是一个类他具有哪些自身的属性。对于room类来说房间数量代表的是多个对象,已经算是实例化了。还有ww()成员方法也不是room类来实现,成员方法可以看成是一种行为。对于room类来说它不具有这样的行为。
问题2:类类型出现空指针
class hotle{
room room;
hotle(){
room = new room();
}
hotle(room room){
this.room = room;
}
//查看房间
void show(){
room.ww();
}
//办理入住
void in(int i,String condition){
if (i>=0&&i<=19 || room.rooms[i].condition == null){
room.rooms[i].condition = condition;
System.out.println("入住成功");
}else {
System.out.println("非法选择");
}
}
void out(){
System.out.println("请输入你的名字");
Scanner scanner = new Scanner(System.in);
String next = scanner.next();
System.out.println("请选择你的房间号");
Scanner scanner1 = new Scanner(System.in);
int i = scanner.nextInt();
if (i>=0&&i<=19 || this.room.rooms[i].condition == null){
this.room.rooms[i].condition = null;
}else {
System.out.println("非法选择");
}
}
if判断中的类类型没有创建出来。hotel中没有创建 room[] rooms类型的数组(写在了room类上了),而且调用 hotle()构造方法时候里面的room()没有初始化数组,导致空指针。
如下是AI检查的结果
发生空指针异常的原因是在代码中使用了未初始化或者为空的对象引用。在你提供的代码中,可能会发生空指针异常的地方有:
-
在
hotle
类的构造函数中,你创建了一个room
对象,并将其赋值给room
属性。如果room
类的构造函数没有正确初始化rooms
数组,那么在调用show()
方法时可能会发生空指针异常。 -
在
in()
方法中,你通过room.rooms[i]
访问了房间数组中的元素对象。如果该元素对象为空(未初始化),那么在尝试访问其属性condition
时会发生空指针异常。 -
在
out()
方法中,同样存在类似的问题。通过this.room.rooms[i]
访问房间数组中的元素对象,如果该元素对象为空(未初始化),那么在尝试访问其属性condition
时会发生空指针异常。
为了解决这个问题,你可以在创建room
对象时确保正确初始化rooms
数组,并在使用数组元素前进行空值检查。例如,在in()
和out()
方法中,可以添加条件判断来避免空指针异常。例如,可以使用类似以下代码:
if (i >= 0 && i <= 19 && room.rooms[i] != null) {
// 执行操作
} else {
// 处理异常情况
}
通过这种方式,你可以在访问对象属性之前检查对象是否为空,从而避免空指针异常的发生。