首页 > 关于java数组例子的疑惑

关于java数组例子的疑惑

public class 投票统计 {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(System.in);
    int x;
    int[] numbers = new int[10];//创建数组
    x = in.nextInt();
    while(x!=-1){
        if(x>=0&&x<=9){
            numbers[x] = numbers[x] + 1;//数组参与运算
        }
        x = in.nextInt();
    }
    for(int i=0;i<numbers.length;i++){
        System.out.println(i+":"+numbers[i]);//遍历数组输出
    }
}

}
上面这个例子看不懂唉,求大神点拨


请看注释,其实运行一下这个程序就明白是怎么回事儿了。

public static void main(String[] args) {
        //创建一个Scanner对象,用于从键盘输入来读取。
        Scanner in = new Scanner(System.in);
        int x;
        /*
        这个数组中存储的十个int,可以理解为10个候选人的ID号,或者名称。
        整个投票的过程,就是这10个int从0开始+1。
         */
        int[] numbers = new int[10];//创建数组
        //从键盘输入读取一个整形,这个整形数值代表的就是10个候选人其中之一的ID,对应到数组,就是数组索引值。
        x = in.nextInt();
        /*
        开始循环,如果输入-1,则结束投票,并遍历数组,打印投票结果。
        如果输入的是0-9中任何一个数字,则代表该候选人票数+1。
         */
        while(x!=-1){
            if(x>=0&&x<=9){
                numbers[x] = numbers[x] + 1;//数组参与运算
            }
            x = in.nextInt();
        }
        for(int i=0;i<numbers.length;i++){
            System.out.println(i+":"+numbers[i]);//遍历数组输出
        }
    }

投票者从控制台输入要投票的号数,假如说投3号,那么程序中的x = 3, 然后把3号的票数加一numbers[x] = numbers[x] + 1;
最后打印出每个人得到的票数。

【热门文章】
【热门文章】