import java.util.Random; public class TestCount { public static void main(String[] args) { int[] arr = new int[100]; int count1 = 0; int count2 = 0; int count3 = 0; int count4 = 0; int count5 = 0; Random r = new Random(); for (int i=0; i<arr.length; i++){ arr[i] = r.nextInt(10)+1; if (arr[i]%2==0){ i--; //覆盖前一个的元素 continue; } System.out.print(arr[i]+" "); if (arr[i]==1){ count1++; continue; } if (arr[i]==3){ count2++; continue; } if (arr[i]==5){ count3++; continue; } if (arr[i]==7){ count4++; continue; } if (arr[i]==9){ count5++; continue; } } System.out.println(); System.out.println("there are "+count1+" one"); System.out.println("there are "+count2+" three"); System.out.println("there are "+count3+" five"); System.out.println("there are "+count4+" seven"); System.out.println("there are "+count5+" nine"); }} 我只能做到这里,感觉很累赘,请大家指点,多谢多谢。
牺牲效率的话,用hashmap ,1000个也没有问题
2分查找,。。
简单sql查询:如学生表,老师表,课程表,成绩表 及联查找
笔试经常考的
import java.util.Random;
public class TestCount { public static void main(String[] args) {
int[] arr = new int[100];
int count1 = 0;
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
Random r = new Random();
for (int i=0; i<arr.length; i++){
arr[i] = r.nextInt(10)+1;
if (arr[i]%2==0){
i--; //覆盖前一个的元素
continue;
}
System.out.print(arr[i]+" ");
if (arr[i]==1){
count1++;
continue;
}
if (arr[i]==3){
count2++;
continue;
}
if (arr[i]==5){
count3++;
continue;
}
if (arr[i]==7){
count4++;
continue;
}
if (arr[i]==9){
count5++;
continue;
}
}
System.out.println();
System.out.println("there are "+count1+" one");
System.out.println("there are "+count2+" three");
System.out.println("there are "+count3+" five");
System.out.println("there are "+count4+" seven");
System.out.println("there are "+count5+" nine"); }}
我只能做到这里,感觉很累赘,请大家指点,多谢多谢。
public class Test{
public static void main(String args[]) {
//为了看结果方便,我把数组长度设为20:
int[] arr=new int[20];
Random rand=new Random();
//计数器数组,counters[0]用来统计1的个数,counters[1]用来统计[3]的个数:
int[] counters=new int[5];
//下面随机产生100个1,3,5,7,9:
for(int i=0;i<arr.length;i++){
arr[i]=2*(rand.nextInt(5)+1)-1;
}
System.out.println("原数组为:\n"+Arrays.toString(arr));
//下面是统计。虽然下面的循环和上面的循环可以合在一起,但逻辑不同,所以我没有合并:
for(int i=0;i<arr.length;i++){
counters[arr[i]/2]++;
}
//下面把结果打印出来:
for(int i=0;i<counters.length;i++){
System.out.println("数组中值为"+(2*i+1)+"的元素个数是"+counters[i]+"个");
}
}F:\java>java Test
原数组为:
[7, 7, 7, 5, 3, 9, 3, 7, 7, 1, 3, 1, 5, 5, 1, 3, 3, 3, 3, 7]
数组中值为1的元素个数是3个
数组中值为3的元素个数是7个
数组中值为5的元素个数是3个
数组中值为7的元素个数是6个
数组中值为9的元素个数是1个
肥虫的 代码中:
counters[arr[i]/2]++;
System.out.println("数组中值为"+(2*i+1)+"的元素个数是"+counters[i]+"个");
就可以解决你的疑问。。
int[] counters=new int[10];//下标为0 2 4 6 8的元素不用.统计时:
for(int i=0;i<arr.length;i++){
counters[arr[i]]++;
}
也可以.打印结果:for(int i=1;i<conters.length;i+=2){
System.out.println("值为"+i+"的个数是:"+counters[i]);
}