java - 为什么我的条件从来没有满足过?

标签 java arrays for-loop linear-search

<分区>

在我的 for 循环的底部获取战利品。这可能是一个简单的逻辑错误,但由于某种原因从未满足“如果”条件。很抱歉问了一些基本的问题,但我已经搜索了又搜索,但似乎找不到答案。感谢您帮助菜鸟。

Scanner scan = new Scanner(System.in);

    System.out.println("How large would you like the array to be? (number)");
    int arraySize = scan.nextInt();
    scan.nextLine();
    String [] myArray = new String [arraySize];
    int i = 0;

    if (arraySize <= 0 ) {
        System.out.println("Please enter a positive integer for the array size. Rerun program when ready.");
    } else {
        while (i < myArray.length) {
            System.out.println("Please type a string to be entered in the array");
            myArray[i] = scan.nextLine();
            i++;
        }
    System.out.println("Array contents: " + Arrays.toString(myArray));
    }
    System.out.println("What element would you like would you like to find in the array by performing a linear search?");
    String search = scan.nextLine();

    for (int j = 0; j < myArray.length; j++) {
        if (myArray[j] == search){
            int location = j + 1;
            System.out.println("The element, " + search + " was found in the array, in which the linear search looped " + location + " times to find it." );
            j = myArray.length;
        }
    }

最佳答案

您应该始终使用 .equals() 而不是 == 运算符进行字符串比较。 == 运算符只有在两个引用都指向同一个 String 实例时才会评估为真。要检查字符串内容是否相等,您可以使用 .equals()equalsIgnoreCase()

所以改变你的搜索条件

if (myArray[j] == search)

if (myArray[j].equals(search))

关于java - 为什么我的条件从来没有满足过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24870074/

相关文章:

java - 如何禁用DEBUG日志

arrays - 将向量转换为 3 维矩阵

java - 通过数组列表搜索? java

python - 获取python for循环中的第一个和最后一个项目

javascript - JavaScript 中的嵌套 for 循环

java - 在定时循环或其他循环中更新 javafx Pane ?

java - 企业 Java Webstart 分发 : use site-wide accepted certificate to sign a code-signing certificate

java - 在 Java 中 stub 复杂接口(interface)的最简单方法是什么?

java - 这两种将集合转换为数组对象的方法的区别

javascript - 将对象添加到数组