1

ifor ループの値を出力しようとしていますindex(i)が、最後の反復でのみです。エラーが発生するか、 のすべての値が出力されますi。これが私がこれまでに持っているものです:

boolean sequentialSearch(int x) {

       for(int i = 0; i < n; i++)  //n comes from function length()

           if(n != 0) {

               if(list[i] == x) {

                   return true;
               }

               return false;
           }
}
4

5 に答える 5

0

次のような sth が必要だと思います。

boolean sequentialSearch(int x) {
    for(int i=0;i<n;i++) { //n comes from function length()
        if(list[i]==x){   // list comes from somewhere too
            System.out.println(i); // print i
            return true;
        }
    }
    return false;
}

i配列の末尾から最後の可能な開始を出力する必要がある場合:

boolean sequentialSearch(int x) {
    for(int i=n-1;i>=0;i--) { //n comes from function length()
        if(list[i]==x){   // list comes from somewhere too
            System.out.println(i); // print i
            return true;
        }
    }
    return false;
}
于 2013-08-06T14:56:25.897 に答える
0

から繰り返すのではなく、なぜ i!=0 をチェックするのかi=1;

for(int i = 1; i < n; i++) 
 {
    if(list[i] == x) 
    { 
        return true;
    }
    return false;
 }

これははるかに簡単です。:-)

于 2013-08-06T14:57:05.290 に答える
0

iブール値を出力して返しますか? はnot found-1によく使用されるため、これを 2 つのメソッドに分割してください。Webアプリケーションのように利用できないシステムであっても、目的に合わせて検索できるようになりました。System.out

boolean sequentialSearch(int x) {
    for(int i = 0, n = list.length; i < n; i++) { 
        if(list[i] == x) {
            return i;
        }
    }
    return -1;
}

// Later
int index = sequentialSearch(y);
if (index != -1) {
    System.out.println(y + " found at index " + index);
} else {
    System.out.println(y + " not found");
}    
于 2013-08-06T15:18:49.413 に答える