以下是我在程序中使用的方法的代码
private static void findRoom(String[] hotel) {
Scanner sc = new Scanner(System.in);
System.out.println("Press Q to exit program and W to go back to menu");
System.out.println("Enter name of customer that needs to be found");
String name = sc.nextLine();
if (name.equalsIgnoreCase("q")){
System.exit(0);
}else if(name.equalsIgnoreCase("w")){
return;
}
boolean found = false;
for (int i = 1; i < hotel.length; i++) {
if (hotel[i].equalsIgnoreCase(name)) {
System.out.println("Room number of " + name + " is " + i);
found = true;
break;
}
}
if (found == false) {
System.out.println("Such a customer does not exist. Please enter valid name");
}
}
在第8行,我想要做的是如果用户输入字母“w”或“W”,那么程序应退出方法并返回主方法。但是,而不是返回我的程序所做的是重新启动方法
以下是控制台上的内容:
按Q退出程序,按W返回菜单 输入需要找到的客户名称 w ^ 按Q退出程序,按W返回菜单 输入需要找到的客户名称 w ^ 按Q退出程序,按W返回菜单 输入需要找到的客户名称
像这样它永远运行
如何让程序返回main方法?
以下是主要方法
public static void main(String[] args) throws IOException {
String roomName = null;
int roomNum = 0;
Scanner sc = new Scanner(System.in);
String[] hotel = new String[11];
initialise(hotel);
System.out.println("Select option: ");
System.out.println("E: Display Empty rooms");
System.out.println("D: Delete customer from room");
System.out.println("F: Find room from customer name");
System.out
.println("S: Store program array data into a plain text file");
System.out
.println("L: Load program data back from the file into the array");
System.out.println("O: View rooms Ordered alphabetically by name.");
System.out.println("Q : Exit program");
String input = sc.next();
while (true) {
if ((input.equals("Q")) || (input.equals("q"))) {
System.exit(0);
}
if ((input.equals("E")) || (input.equals("e"))) {
displayEmpty(hotel);
}
if ((input.equals("D")) || (input.equals("d"))) {
deleteCustomer(hotel);
}
if ((input.equals("F")) || (input.equals("f"))) {
findRoom(hotel);
}
if ((input.equals("S")) || (input.equals("s"))) {
storeArray(hotel);
}
if ((input.equals("L")) || (input.equals("l"))) {
loadArray(hotel);
}
if ((input.equals("O")) || (input.equals("o"))) {
hotel = sortArray(hotel);
veiwRooms(hotel);
}
if ((input.equals("A")) || (input.equals("a"))) {
addCustomer(hotel, roomNum, roomName);
}
if ((input.equals("V")) || (input.equals("v"))) {
veiwRooms(hotel);
}
}
}
好的,我找到了解决方案。更改while(true)语句的位置