【发布时间】:2016-01-29 15:08:45
【问题描述】:
我一直在研究几个数组示例。一路上取得了一些成功。这几天我一直在研究这段代码,只是无法理解循环体中这个增量的目的。它通常是从它被隔离时开始制作的,但这次我不知道它做了什么。
计算 1 到 10 之间整数的出现次数
Scanner input = new Scanner(System.in);
int[] count = new int[10];
System.out.println("Enter the integers between 1 and 10: ");
// Read all numbers
// 2 5 6 5 4 3 9 7 2 0
for (int i = 0; i < count.length; i++)
{
int number = input.nextInt();
count[number]++; //this is the one that perplexes me the most
}
//Display result
for (int i = 0; i < 10; i++)
{
if (count[i] > 0)
{
System.out.println(i + " occurs " + count[i]
+ ((count[i] == 1) ? " time" : " times"));
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!这句话“..这次我不知道它做了什么..”是否也意味着你不知道你正在使用什么编程语言?如果你这样做,请edit你的问题,至少为它添加一个标签。只要您这样做,为什么不阅读How do I ask a good question? 并尝试改进一下。
-
count[number]++; //this is the one that perplexes me the most– 这有什么令人困惑的地方?有一个名为count的数组,对于用户输入的每个数字,相应的数组元素都会加一——这样最后这个数组就可以知道每个数字被用户输入了多少次. -
当我看到这样的代码时你会看到 count[number]++;我通常认为向索引添加一个数字是因为它会向前移动而不是你解释它的方式。
-
当您可以通过 for 循环将 10 个整数添加到数组中时,为什么还要手动输入 1 到 10 之间的整数?我认为该字符串应为“输入 10 个整数”,因为这就是代码实际在做的事情