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]);//遍历数组输出
}
}
}
上面这个例子看不懂唉,求大神点拨
PHP中文网2017-04-17 13:32:44
Please read the comments. In fact, you will understand what is going on if you run this program.
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]);//遍历数组输出
}
}
大家讲道理2017-04-17 13:32:44
The voter enters the number to vote from the console. If he votes for No. 3, then x = 3 in the program, and then adds one to the number of votes for No. 3numbers[x] = numbers[x] + 1;
Finally print out the number of votes each person got.