Java 在预订系统中搜索数组以查找值

Java 在预订系统中搜索数组以查找值,java,arrays,Java,Arrays,我正在制作一个通过控制台显示的酒店预订系统。系统应允许用户选择最多10个房间号1-10,并提供正在预订的客户姓名。下面我提出了一种在程序运行时保持所有房间为空的方法 private static void initialise(String hotelRef[]) { for (int x = 0; x < 10; x++) { hotelRef[x] = "EMPTY"; } } 下面我试图通过酒店系统阵列查看是否找到了客户。此时,拾取了n个元素。有人能告诉我如何搜索元

我正在制作一个通过控制台显示的酒店预订系统。系统应允许用户选择最多10个房间号1-10,并提供正在预订的客户姓名。下面我提出了一种在程序运行时保持所有房间为空的方法

private static void initialise(String hotelRef[]) {
for (int x = 0; x < 10; x++) {
    hotelRef[x] = "EMPTY";
    }
}
下面我试图通过酒店系统阵列查看是否找到了客户。此时,拾取了n个元素。有人能告诉我如何搜索元素吗

  System.out.println("Please enter the customer name:");
            String findCust = input.next();
            for (int x = 0; x < 10; x++) {
                if (findCust.equals(hotel[x])) {
                    System.out.println("Room " + x + " is occupied by " + hotel[x]);

                } else {
                    System.out.println("Customer is not found.");
                    exitToMenu(hotel);

                }
            }

循环在第一次迭代后停止。您需要将代码更改为以下内容:

int y = -1;
 for (int x = 0; x < 10; x++)
 {
  if (findCust.equals(hotel[x]))
  {
            y = x;
            break;

  }
}
  if(y!=-1)
  {
  System.out.println("Room " + x + " is occupied by " + hotel[x]);

  } else 
 {
  System.out.println("Customer is not found.");
  exitToMenu(hotel);

 }

使用Arrays.aslist将数组转换为列表,并使用.containsObject方法检查对象是否存在

if (findCust.equals(hotel[x])) {
     System.out.println("Room " + x + " is occupied by " + hotel[x]);

} else {
     System.out.println("Customer is not found.");
     exitToMenu(hotel);

}

在上面的代码中,hotelRef数组和hotel数组是相同的吗?如果不是,请尝试使用hotelRef[]而不是hotel[]。

您需要重新构造代码。如果有匹配项,就停止循环。然后,在循环之后,使用布尔值说明房间是否已被占用,或者在返回菜单之前是否未找到客户。尽管我建议引入一种按名称搜索房间的方法。那么代码是可重用的。但我猜你是编程新手,所以这不是暂时的,到目前为止似乎还不起作用。不过还是要谢谢你。到目前为止似乎还不起作用。不过还是要谢谢你。hotel和hotelRef是指同一个数组吗?