打印对应的数组索引

时间:2018-11-09 02:30:10

标签: java arrays indexing

int diff = gamesA[0] - gamesB[0];
    for(int i = 0; i < gamesA.length; i++)
    {
        int y = Math.abs(gamesA[i] - gamesB[i]);
        if(y > diff)
        diff = y;
    }
    System.out.println("In quarter finals, largest deficit of schoolB was " 
+ diff + " in the" +_____+ "game.");

我正在尝试打印出赤字最大的数组中的索引。不是值,而是它所在的索引。一切都有帮助。“ ____”是需要放置所需代码的地方。

3 个答案:

答案 0 :(得分:0)

只需声明变量即可在循环外存储索引

nvlink fatal   : Internal error: reference to deleted section
Makefile:83: recipe for target '/home/mml/pytorch/build/nccl/obj/collectives/device/devlink.o' failed
make[5]: *** [/home/mml/pytorch/build/nccl/obj/collectives/device/devlink.o] Error 1
Makefile:45: recipe for target 'devicelib' failed
make[4]: *** [devicelib] Error 2
Makefile:24: recipe for target 'src.build' failed
make[3]: *** [src.build] Error 2
CMakeFiles/nccl_external.dir/build.make:110: recipe for target 'nccl_external-prefix/src/nccl_external-stamp/nccl_external-build' failed
make[2]: *** [nccl_external-prefix/src/nccl_external-stamp/nccl_external-build] Error 2
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/nccl_external.dir/all' failed
make[1]: *** [CMakeFiles/nccl_external.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....

[ 73%] Building CXX object caffe2/CMakeFiles/caffe2.dir/transforms/conv_to_nnpack_transform.cc.o
[ 73%] Linking CXX shared library ../lib/libcaffe2.so
[ 73%] Built target caffe2
Makefile:138: recipe for target 'all' failed
make: *** [all] Error 2

答案 1 :(得分:0)

通过以下方式:

int diff = gamesA[0] - gamesB[0];
int i; // declare it outside the loop to make it available after loop ends.
    for(i = 0; i < gamesA.length; i++)
    {
        int y = Math.abs(gamesA[i] - gamesB[i]);
        if(y > diff)
        diff = y;
    }
    System.out.println("In quarter finals, largest deficit of schoolB was " 
+ diff + " in the" +(i+1)+ "game.");
//i+1 for indexing from 1 onward .. or use just i for indexing 0 onward.

答案 2 :(得分:0)

到目前为止,其他答案将始终显示最后一个位置。试试这个:-

int diff = gamesA[0] - gamesB[0];
int pos = 0;
for (int i = 0; i < gamesA.length; i++) {
    int y = Math.abs(gamesA[i] - gamesB[i]);
    if (y > diff) {
        diff = y;
        pos = i;
    }
}
System.out.println("In quarter finals, largest deficit of schoolB was "
        + diff + " in the" + pos + "game.");