【发布时间】:2016-05-09 09:44:22
【问题描述】:
这个程序使用一个二维数组来记录开放和预订的房间。程序在开始和每次改变数组之后都会显示二维数组。索引值代表房间号并针对开放房间显示。预定房间显示预定房间的人的姓名。程序将继续运行,直到用户输入“Q”。
对我来说一切似乎都很好,除了在 main 方法中执行一次循环后,即使用户没有输入“Q”,程序也会停止运行。我也试过用 while(true) 来做,但它仍然不起作用。我真的希望有人可以帮助我。
public static void main (String [] args)
{
Scanner kb = new Scanner (in);
out.print("Enter row size: ");
int row = kb.nextInt();
out.print("Enter column size: ");
int col = kb.nextInt();
kb.nextLine();
String [][]rooms = roomInIt(row, col);
printMatrix(rooms);
String a="";
for(;;)
{
out.print("Would you like to reserve or release a room? Type Q to exit ");
a = kb.nextLine();
if (a.equalsIgnoreCase("reserve"))
{
out.print("How many rooms would you like to reserve? ");
int num = kb.nextInt();
reserveRooms(rooms, num);
}
else if (a.equalsIgnoreCase("release"))
{
out.print("How many rooms would you like to release? ");
int x = kb.nextInt();
releaseRooms(rooms, x);
}
else if (a.equalsIgnoreCase("Q"));
break;
}
}
public static void printMatrix(String[][]rooms)
{
for(int r=0; r<rooms.length; r++)
{
for (int c=0; c<rooms[r].length; c++)
out.print("["+r+","+c+"] "+rooms[r][c]+"\t");
out.println();
}
}
public static String[][] roomInIt(int row, int col)
{
String [][]rooms = new String [row][col];
for(int r=0; r<rooms.length; r++)
for (int c=0; c<rooms[r].length; c++)
rooms[r][c]="open";
return rooms;
}
public static void reserveRooms(String [][]room, int num)
{
Scanner kb = new Scanner(in);
for(int i=0; i<num; i++)
{
out.print("Enter name: ");
String name = kb.nextLine();
out.print("Enter the room number (row and column separated by a space) ");
int r=kb.nextInt();
int c=kb.nextInt();
kb.nextLine();
while (r<0 || r>room.length || c<0 || c>room[r].length || !room[r][c].equals("open"))
{
out.print("Invalid room number. Enter another room number (row and column separated by a space) ");
r=kb.nextInt();
c=kb.nextInt();
kb.nextLine();
}
room[r][c] = name;
}
printMatrix(room);
}
public static void releaseRooms(String [][]room, int x)
{
int r, c;
Scanner kb = new Scanner(in);
for(int i=0; i<x; i++)
{
out.print("Enter name: ");
String name = kb.nextLine();
out.print("Enter the room number (row and column separated by a space) ");
r=kb.nextInt();
c=kb.nextInt();
kb.nextLine();
while(r<0 || r>room.length || c<0 || c>room[r].length)
{
out.print("Invalid room number. Enter another room number (row and column separated by a space) ");
r=kb.nextInt();
c=kb.nextInt();
kb.nextLine();
}
room[r][c] = "open";
}
printMatrix(room);
}
【问题讨论】:
标签: java arrays loops multidimensional-array infinite-loop