首先肯定要创建一个Room类:
package faker;
public class Room {
String name;
double price;
String desc;
public Room() {
}
public Room(String name, double price, String desc) {
this.name = name;
this.price = price;
this.desc = desc;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
再创建一个RoomOperator类,用来实现用户增加和展示房间的功能。
package faker;
import java.util.ArrayList;
import java.util.Scanner;
public class RoomOperator {
static ArrayList<Room> list=new ArrayList<>();
public static void addroom(){ //增加房间
Room room=new Room();
Scanner sc=new Scanner(System.in);
System.out.println("请输入房间名称:");
String next = sc.next();
room.setName(next);
System.out.println("房间价格:");
double price = sc.nextDouble();
room.setPrice(price);
System.out.println("描述房间");
String desc = sc.next();
room.setDesc(desc);
System.out.println("添加结束");
list.add(room); //把创建好的对象放到集合中
}
public void showRoom(){ //展示房间
for (int i = 0; i < list.size(); i++) {
Room r=list.get(i); //集合中存放的是Room对象,先返回对象,再将对象中的属性展示出来
System.out.println(r.getName());
System.out.println(r.getPrice());
System.out.println(r.getDesc());
System.out.println("-----------------------");
}
}
public void start(){ //让用户选择添加和展示房间,而不是系统自动生成
while(true){
System.out.println("请选择功能");
System.out.println("1.增加房间");
System.out.println("2.展示房间信息");
System.out.println("3.退出");
System.out.println("请选择您的操作");
Scanner sc=new Scanner(System.in);
String data=sc.next();
switch(data){
case "1": //防止用户输入字母导致系统崩溃,所以使用字符类型
addroom();
break; //跳出switch循环,用户可以继续选择功能
case "2":
if(list.size()==0){ //没有房间就让用户重新选择功能
System.out.println("什么都没有");
break;
}
showRoom();
break; //跳出switch循环,用户可以继续选择
case "3":
System.out.println("下次再来哦");
return; //跳出方法体,结束所有循环
default:
System.out.println("你输入的数字有误");
break;
}
}
}
}
最后创建一个Java类,实现所有功能:
package faker;
import java.util.ArrayList;
public class List {
public static void main(String[] args) {
RoomOperator operator=new RoomOperator(); //创建RoomOperator对象
operator.start(); //调用start方法,实现功能
}
}