酒店管理系统分析:
复习:
1.类和对象
类:所有同种对象共同拥有属性和行为,抽象出来成为类
属性:成员变量
行为:成员方法
对象:符合类的特征的实例化独立个体
new student();
构造方法:(可以没有修饰词[public])
无参/有参
没有返回值类型
this:当前对象(只能放在第一行)
可以调用成员变量和成员方法
成员变量和局部变量的区别
1)个数
成员变量 - 对象决定
局部变量 - 声明个数
2)初始化
3)位置
4)JVM内存中
栈:局部变量/临时变量
堆:引用类型的真正数据 - 成员变量
方法区:类相关的信息
案例分析:
酒店管理系统:
酒店类:
成员变量:
房间、顾客
成员方法:
入住方法、退房方法、查房方法
房间类:
成员变量:
房间号、顾客
成员方法:
默认添加无参方法
顾客类:
成员变量:
身份证号、名字
成员方法:
默认添加无参方法
public class Guest {
//成员变量
String name;
int id;
//无参构造器
Guest(){
}
//有参构造器 - 新来酒店的客户需不需要有名字/需不需要id
Guest(String name){
this.name = name;
}
//成员方法
}
public class Room {
//成员变量
int num;
//客户
Guest guest;
//无参构造器 - 初始化成员变量
Room(){
}
//有参构造器 - 问创建出来的房间需不需要有房间号
Room(int num){
this.num = num;
}
//成员方法
}
public class Hotel {
//成员变量
//房间 - 二维数组, 有5层,每层5个房间 - null
Room[][] rooms = new Room[5][5];
//
Hotel(){
//i表示 有多少层
for (int i = 0; i < rooms.length; i++) {
//j 表示 i 层中有多少个房间
// 1001 ->
for (int j = 0; j < rooms[i].length; j++) {
//房间号
int roomNum = (i + 1) * 1000 + j + 1;
rooms[i][j] = new Room(roomNum);
//System.out.print(rooms[i][j].num);
}
}
}
//成员方法
//入住 - in
void in(int roomNum, String name){
//得到 i层
int i = roomNum / 1000 - 1;
//得到 j层
int j = roomNum % 1000 - 1;
if(rooms[i][j].guest == null){
// 2002
rooms[i][j].guest = new Guest(name);
System.out.println(name + "入住" + roomNum);
}else{
System.out.println("此房间已住人");
}
}
//退房
void out(int roomNum){
int i = roomNum / 1000 -1;
int j = roomNum % 1000 -1;
if(rooms[i][j].guest != null){
rooms[i][j].guest = null;
}else{
System.out.println("此房间已空");
}
}
//查房 \t -> tab键盘
void show(){
//查看 有i层
for (int i = 0; i < rooms.length; i++) {
//查看 第 i层 的第j个房间减
for (int j = 0; j < rooms[i].length; j++) {
System.out.print(rooms[i][j].num + "\t");
}
System.out.println();
for (int j = 0; j < rooms[i].length; j++) {
if(rooms[i][j].guest != null){
System.out.print(rooms[i][j].guest.name + "\t");
}else{
System.out.print(rooms[i][j].guest + "\t");
}
}
System.out.println();
}
}
}
import java.util.Scanner;
/*
普通类 - 放主方法
*/
public class Main {
public static void main(String[] args) {
//创建酒店类的对象
Hotel hotel = new Hotel();
Scanner console = new Scanner(System.in);
/*hotel.in(2002,"张三");
hotel.out(2002);
hotel.in(2002,"sili");
hotel.show();*/
while (true) {
//获取需要的指令
System.out.println("请输入指令:show查看,in入住,out退房,exit退出程序");
String command = console.next();
switch (command) {
case "in":
System.out.println("请输入房间号:");
int roomNum = console.nextInt();
System.out.println("请输入入住的客户名:");
String name = console.next();
hotel.in(roomNum, name);
break;
case "out":
System.out.println("请输入要退房的房间号:");
int roomNum1 = console.nextInt();
hotel.out(roomNum1);
break;
case "show":
hotel.show();
break;
case "exit":
//System.exit(0);//强制退出程序
//break loop;
return;
default:
System.out.println("输入指令有误,请重新输入");
}
}
}
}