Java - 在数组中查找元素

我目前正在尝试弄清楚如何搜索我的数组以查找数组中的特定元素。用户将输入他们要查找的名称,我的程序应该将他们所坐的座位返回给用户。添加乘客是通过另一种方法完成的。所以,如果我有一个叫“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;

        }

    }

}


犯罪嫌疑人X
浏览 112回答 1
1回答

慕桂英3389331

你应该摆脱,else否则你只评估你的数组的第一个索引并传递所有其余的。以下应该发挥它的魅力:您基本上浏览了所有乘客的列表,只有当没有一个与输入相对应时,您才声明未找到该乘客。for (int i = 0; i < airplaneRef.length; i++) { // for i, if i is less than the length of the array airplaneRef, increment i.&nbsp; &nbsp; if (airplaneRef[i].equalsIgnoreCase(passengerName)) { // iterates through all elements in the array, ignoring case sensitivity and looks for the passenger.&nbsp; &nbsp; &nbsp; &nbsp; int seat = i;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(passengerName + " is sitting in seat s" + seat); // prints name of passenger and what seat they are sitting in.&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }}System.out.println("Passenger not found.");
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java