通过从头开始观察元素,数组b中的字符改变了多少次

public static  int changeSign(int [] b) {


    int counter=0 ;


    for(int i=0;i<b.length;i++) {


        if(b[i]>0 && b[i+1]<0) {


            counter++;


        }

        if(b[i]<0 && b[i+1]>0) {


            counter++;


        }


    }


    return counter;

    }

例如,u 10, -4, 12, 56, -8, -9字符改变3次数


慕村9548890
浏览 33回答 1
1回答

HUX布斯

你遇到的问题是ArrayIndexOutOfBoundsException因为当你尝试访问which isi时,这是不可能的,因为索引从0开始,所以你需要在之前停止一步。b.length-1b[i+1]b[b.length]另外,为了只得到一个条件,您可以相乘并查看结果的符号:public static int changeSign(int[] b) {&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; for (int i = 0; i < b.length - 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (b[i] * b[i + 1] < 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return counter;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java