为什么我的病情从未得到满足?

时间:2014-07-21 16:30:06

标签: java arrays for-loop linear-search

在我的for循环中取一个底部的战利品。这可能是一个简单的逻辑错误,但出于某种原因'if'条件从未得到满足。很抱歉问基本的东西,但我搜索和搜索,似乎无法找到答案。谢谢你帮助一个菜鸟。

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;
        }
    }

2 个答案:

答案 0 :(得分:4)

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

所以改变你的搜索条件

if (myArray[j] == search)

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

答案 1 :(得分:2)

您正在使用==代替.equals而不检查字符串是否相等。 .equals将检查值是否相等,而不仅仅是这样的参考数字:

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