1

在我的 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;
        }
    }
4

2 回答 2

4

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

因此,将您的搜索条件从

if (myArray[j] == search)

if (myArray[j].equals(search))
于 2014-07-21T16:31:19.117 回答
2

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

if( myArray[j].equals(search)){
于 2014-07-21T16:31:39.893 回答