【问题标题】:Java - Finding An Element Within An ArrayJava - 在数组中查找元素
【发布时间】:2019-03-10 18:55:47
【问题描述】:

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

【问题讨论】:

  • 您的数组中可能有 Tim,但由于使用 next 而不是 nextLine,您没有 Tim Jones i>.
  • 这就是为什么你应该学习如何使用调试器。

标签: java arrays indexing


【解决方案1】:

你应该去掉 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.");

【讨论】:

    猜你喜欢
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多