java无限循环在程序中无法正常工作
该程序使用2D数组记录开放和保留的房间。程序在开始时和每次更改阵列后都会显示2D阵列。索引值表示房间号,并为开放式房间显示。预订房间显示预订房间的人的姓名。程序将继续运行,直到用户输入“Q”
对我来说,一切似乎都很好,除了在主方法中循环一次之后,即使用户没有输入“Q”,程序也停止运行。我也试过用while(真的)来做,但仍然不起作用。我真的希望有人能帮我
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);
}
# 1 楼答案
而不是使用
为什么不使用