我是初学者,我尝试解决一个家庭作业,我有一个java控制台项目,我应该为每个类创建一个包,在这个包中,它必须有类模型,一个接口,和一个实现接口中定义的所有方法的类,这意味着每个包将有3个类。现在我有两个包,第一个包包含:room.java,iroom.java,roomt.java第二个包包含应用程序类app.java问题是我在应用程序类中有一个菜单,可以让我进入一个room子菜单或退出。客房子菜单包括:
将房间对象保存在roomt.java的arraylist中
显示arraylist中的所有对象。
返回主菜单。
如果我回到主菜单我重新进入房间子菜单,当我选择显示我保存的所有对象时,arraylist是空的,我不知道为什么?如何解决这个问题。课程如下:;
房间.java
/**
*
* @author******
*/
public class Room {
private String id;
private float price;
public Room(){}
public Room(String id, float price){
this.id = id;
this.price = price;
}
public String toString(){
return " ID :"+this.id+"\n"
+" Price : $"+this.price;
}
}
iroom.java文件
/**
*
* @author*******
*/
public interface IRoom {
void save();
void display();
}
室友.java
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author*****
*/
public class RoomT implements IRoom{
Scanner input = new Scanner(System.in);
Scanner num = new Scanner(System.in);
public ArrayList<Room> dbRoom = new ArrayList<>();
Room room = new Room();
public void save(){
System.out.println("Id : ");
String id = input.nextLine();
System.out.println("Price : ");
float price = num.nextFloat();
room = new Room(id, price);
dbRoom.add(room);
}
public void display(){
if(dbRoom.isEmpty()){
System.out.println("Room not saved yet!!!");
}else{
for(Room room: dbRoom){
System.out.println("____________________________________________");
System.out.println(room.toString());
System.out.println("____________________________________________");
}
}
}
}
应用程序.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hotel.app;
import com.hotel.room.*;
import java.util.Scanner;
/**
*
* @author*****
*/
public class App {
public static void main(String[] args) {
int choice;
Scanner input = new Scanner(System.in);
do{
System.out.println("1. For Room Menu. ");
System.out.println("0. For quitt programs.=. ");
choice = input.nextInt();
switch(choice){
case 0 :
System.exit(0);
break;
case 1 :
Scanner num = new Scanner(System.in);
RoomT room = new RoomT();
int choicech;
do{
System.out.println("_______________ROOM MENU_________________________");
System.out.println(" 1. Save a room.");
System.out.println(" 2. Display all rooms.");
System.out.println(" 0. <-back to main menu.");
System.out.println("_____________________________________________________");
choicech = num.nextInt();
switch(choicech){
case 0 :
choicech = 5;
break;
case 1 : room.save();
break;
case 2 : room.display();
break;
default : System.out.println("Incorrect Choice!!!.");
break;
}
}while(choicech<3);
break;
default :
System.out.println("Incorrect!!");
break;
}
}while(choice<2);
}
}
结果
暂无答案!
目前还没有任何答案,快来回答吧!