1

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

2 に答える 2

4

文字列の比較には常に.equals()and not==演算子を使用する必要があります。==operator は、両方の参照が同じ String インスタンスを指している場合にのみ true と評価されます。文字列の内容が等しいかどうかを確認するには、.equals()またはを使用できますequalsIgnoreCase()

したがって、検索条件を次のように変更します

if (myArray[j] == search)

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

文字列が等しいかどうかをチェックしない==代わりにwhichを使用しています。次のような参照番号だけでなく、値が等しいことを確認します。.equals.equals

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