gpt4 book ai didi

java - 无限循环在程序中无法正常工作

转载 作者:行者123 更新时间:2023-11-29 03:00:46 24 4
gpt4 key购买 nike

该程序使用二维数组记录开放和预订的房间。程序在开始时和每次更改数组后显示二维数组。索引值表示房间号,并针对开放房间显示。预订的房间显示预订房间的人的姓名。该程序将继续运行,直到用户输入“Q”。

除了在主方法中执行一次循环后,即使用户没有输入“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);
}

最佳答案

去掉 else if (a.equalsIgnoreCase("Q")); 上的分号

; 结束语句,这意味着 break 总是完成,而不仅仅是当条件满足时。

关于java - 无限循环在程序中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com