投票统计和遍历数组

投票统计

  创建数组后,java会帮你把这个数组里面的所有东西都填成零,默认的初始值是0

  Scanner in = new Scanner(System.in);

        int[]numbers = new int[10];//创建int数组
        int x;
        x = in.nextInt();
        while ( x != -1 ){
        if ( x>=0 && x<=9 ){
            numbers[x]++;}//数组参数运算
            x= in.nextInt();}
  //遍历数组输出
for ( int i=0; i<numbers.length; i++) { System.out.println(i+" : "+numbers[i]); }

 

遍历数组

  遍历数组通常使用的都是for循环,让循环变量i从0到<数组的length,这样的循环体内最大的i正好是数组最大的有效下标

常见的错误:

  循环结束条件是<=数组长度;

  离开循环后,继续用i的值来做数组元素的下标

遍历数组的话,可以使用for循环,建议使用for-each循环,减少代码量

 

读的时候我们是要倒着读的

  对于数组当中的每个元素,取出来那个变量

 for(<类型><变量>:<数组>){

  .........

}

        Scanner in = new Scanner(System.in);
        int[]data = {2,3,5,7,4,9,11,34,28};
        int x = in.nextInt();
        boolean found = false;
        for ( int k : data ) {
            if ( x == k ){
                found = true;
                break;
            }
        }
        if ( found ){
            System.out.println(x+"在其中");
        } else{
            System.out.println(x+"不在其中");
        }

 

posted @ 2022-06-21 13:35  漁夫  阅读(42)  评论(0)    收藏  举报