
业务分析
1、需要一个房间类,包含房间的属性,比如房间编号、房间类型、是否占用。
2、需要一个旅馆类,旅馆有房间,提供的方法需要有 预订房间、打印房间信息、初始化房间、退房。
3、测试类,测试预订房间。
package javasimple; import java.util.Scanner; public class HotelTest {
public static void main(String[] args) {
Hotel h = new Hotel();
h.print();
while(true) {
System.out.println("请输入房间编号:");
Scanner s = new Scanner(System.in);
String no = s.next();
h.order(no);
h.print();
}
}
}
/**
* 旅馆类
* @author haokui
*
*/
class Hotel {
private Room [][]rooms;//旅馆有房间
public Hotel(){
rooms = new Room[5][10];
//初始化旅馆时,展示房间
for (int i = 0; i < rooms.length; i++) {
for (int j = 0; j < rooms[i].length; j++) {
if (i == 0 || i== 1) {
//1、2层为单人间
rooms[i][j] = new Room((i+1)*100 + j + 1 + "","单人间",false);
}
if (i == 2 || i== 3) {
//3、4层为双人间
rooms[i][j] = new Room((i+1)*100 + j + 1 + "","双人间",false);
}
if (i == 4) {
//5层为豪华间
rooms[i][j] = new Room((i+1)*100 + j + 1 + "","豪华间",false);
}
}
}
}
/**
* 打印房间信息
*/
public void print(){
for (int i = 0; i < rooms.length; i++) {
for (int j = 0; j < rooms[i].length; j++) {
System.out.print(rooms[i][j].toString());
}
System.out.println();
}
}
/**
* 预订房间
* @param no - 房间号
*/
public void order(String no){
for (int i = 0; i < rooms.length; i++) {
for (int j = 0; j < rooms[i].length; j++) {
if (rooms[i][j].getNo().equals(no)) {
//找到了要订的房间,把空闲改为占用
rooms[i][j].setIsuse(true);
}
}
}
}
/**
* 退房
* @param no - 房间号
*/
public void cancelorder(String no){
for (int i = 0; i < rooms.length; i++) {
for (int j = 0; j < rooms[i].length; j++) {
if (rooms[i][j].getNo().equals(no)) {
//找到了要退的房间,把占用改为空闲
rooms[i][j].setIsuse(false);
}
}
}
}
}
/**
* 房间类
* @author haokui
*
*/
class Room {
//
private String no;//房间编号
private String type;//房间类型
private boolean isuse;//是否占用
public Room (String no, String type, boolean isuse) {
this.no = no;
this.type = type;
this.isuse = isuse;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isIsuse() {
return isuse;
}
public void setIsuse(boolean isuse) {
this.isuse = isuse;
}
public String toString(){
return "["+no+","+type+","+(isuse ? "占用":"空闲")+"]";
} }
运行如下:
输入要预订的房间号,比如201,,回车,结果
会发现201已经被占用了,退房也是一样的原理。