我目前正在尝试弄清楚如何搜索数组以查找数组中的特定元素。用户将输入他们要查找的名称,我的程序应将用户所坐的座位返回给用户。添加乘客的方法是另一种方法。因此,如果我在座位5上坐着一个叫“蒂姆·琼斯”的人,如果我使用这种方法,我将键入“蒂姆·琼斯”,并且程序应该告诉我蒂姆·琼斯在座位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;
}
}
}
答案 0 :(得分:0)
您应该摆脱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.");