gpt4 book ai didi

Java - 查找数组中的元素

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:39 24 4
gpt4 key购买 nike

我目前正在尝试找出如何搜索数组以查找数组中的特定元素。用户将输入他们想要查找的名字,我的程序应该将他们所坐的座位返回给用户。添加乘客是通过另一种方法完成的。因此,如果我有一个叫“Tim Jones”的人坐在 5 号座位上,如果我使用此方法,我会输入“Tim Jones”,程序应该告诉我 Tim Jones 坐在 5 号座位上。

我得到的当前输出只是 else 语句,无论我如何尝试都找不到乘客。有小费吗?提前致谢。

private static void findPassengerSeat(String airplaneRef[]) {
String passengerName;
Scanner input = new Scanner(System.in);
System.out.println("Enter passenger's name."); // asks user for passenger name.
passengerName = input.next(); // user input stored under variable passengerName.
for (int i = 0; i < airplaneRef.length; i++) { // for i, if i is less than the length of the array airplaneRef, increment i.
if (airplaneRef[i].equalsIgnoreCase(passengerName)) { // iterates through all elements in the array, ignoring case sensitivity and looks for the passenger.
int seat = i;
System.out.println(passengerName + " is sitting in seat s" + seat); // prints name of passenger and what seat they are sitting in.
} else {
System.out.println("Passenger not found.");
break;
}
}
}

最佳答案

您应该删除 else,否则您只会评估数组的第一个索引并传递所有其余索引。

以下内容应该发挥其魅力:您基本上会遍历所有乘客的列表,并且只有当没有一个与输入相对应时,您才会声明找不到该乘客。

for (int i = 0; i < airplaneRef.length; i++) { // for i, if i is less than the length of the array airplaneRef, increment i.
if (airplaneRef[i].equalsIgnoreCase(passengerName)) { // iterates through all elements in the array, ignoring case sensitivity and looks for the passenger.
int seat = i;
System.out.println(passengerName + " is sitting in seat s" + seat); // prints name of passenger and what seat they are sitting in.
return;
}
}
System.out.println("Passenger not found.");

关于Java - 查找数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55091202/

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