先谢谢各位大神,代码如下:
import java.util.Scanner;
import java.util.Calendar;
public class Test {
static int i,j;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("欢迎光临!");
long begin=Calendar.getInstance().getTimeInMillis();
//预定房间
Hostel h=new Hostel();
//调用房间显示方法
h.show();
//选择房间
while(true){
try{
select1();
select2();
//调用房间预订方法
if(h.book(i,j)) break;
}catch (OutIndexOfException e){
e.printStackTrace();
}
}
//退订房间
while(true){
try{
select1();
select2();
if(h.unsubscribe(i,j)) break;
}catch (OutIndexOfException e){
e.printStackTrace();
}
}
System.gc();
long end=Calendar.getInstance().getTimeInMillis();
System.out.println(end-begin);
}
public static int select1() throws OutIndexOfException{
Scanner s1=new Scanner(System.in);
i=s1.nextInt()-1;
// s1.close();
if(i4){
throw new OutIndexOfException("第"+(i+1)+"层没有房间");
}
return i;
}
public static int select2() throws OutIndexOfException{
Scanner s2=new Scanner(System.in);
j=(s2.nextInt())-1;
//s2.close();
if(j9){
throw new OutIndexOfException("第"+(j+1)+"间房不对外预定");
}
return j;
}
}
代码中注释掉的s1,s2方法,如果不注释掉就会爆异常Exception in thread "main" java.util.NoSuchElementException,如果注释掉可以运行,但是扫描器没关闭,感觉不安全!!! 还有个问题是显示问题两个select方法中的i4和j9是i4,j9;