随机产生一组随机数,判断数字的连续性,如果当前数字前后不连续,则输出该数字+空格 如果当前两个数字连续则输出 数字:数字+空格 如果当前三个或者三个以上的数字连续,则输出 第一个开始连续的数字-最后一个连续的数字+空格 例如:假设有一组数字:1,2,4,7,8,9 0,4,5,8,9,10,11,12则要求输出为1:2 4 7-9 0 4:5 8-12 public class Test2{ public static void main(String[]args){ //定义一个测试数组来专门测试 int []a = new int[]{0,2,3,5,6,4,7,8,9,10,0,1,2,3,7,9,8,9,10,12,15,16}; //调用方法 Test2.print(a); } /** * 定义方法 * @param a */ public static void print(int[]a){ /** * * */ int num = 0; //num记录了数组中每次比较数字连续的次数 int index=0; //记录当前数组的下标 int temp= a[0]; temp = a[0]; //TEMP用来记录重新开始比较的第一个数字 /** * 循环判断 //循环比较 */ for(int i=0;i<a.length-1;i++){ index = i; /** * 循环判断,当连续的时候继续往下判断 * 当不连续的时候做出处理 * 如果不连续 * 判断当前连续的次数,按照题目输出 */ //记录数组下标 if(a[i]==a[i+1]-1){ num++; //记录数字连续的次数 continue; //如果判断连续则继续往下判断 }else{ //否则不不连续的话进行处理 if(num==0){ //如果当前判断连续的次数等于0,就表示我要输出一个当前数字就可以了 System.out.print(a[index]+" "); //输出当前数字 temp = a[index+1]; //记录下次开始的数字 num = 0; //把连续相等的次数重置为0.方便下次的记录 } else if(num==1){ //如果相等的次数为1,表示我要输出两个数字 System.out.print(a[index-1]+":"+a[index]+" "); //输出的数字是当前数字和前一个数字 temp = a[index+1]; //记录下次开始的数字 num = 0; //把连续相等的次数重置为0.方便下次的记录 } //这里表示数字连续的次数大于等于两次 else { System.out.print(temp+"--"+a[index]+" "); //输出开始和结束的数字 temp = a[index+1]; //记录下次开始的数字 num=0; //把连续相等的次数重置为0.方便下次的记录 } } } //输出最后一次的判断,注意最后一个数字的输出下标都要相应加1 if(num==0){ System.out.print(a[index+1]+" "); temp = a[index+1]; num = 0; } else if(num==1){ System.out.print(a[index]+":"+a[index+1]+" "); temp = a[index+1]; num = 0; } else { System.out.print(temp+"--"+a[index+1]+" "); temp = a[index+1]; num=0; } } }