int[] binArray = new int[100];
int bins = 10;
int numOfIterations = 100/bins;
int binElement = 0;
for (int i=0; i<numOfIterations; i++) {
binElement = binElement + bins;
binElement = binArray[i];
System.out.println(binArray[i]);
}
继续打印: 0 0 0 0 0 0 0 0 0 0
尝试打印:0,10,20,30,40,50,60,70,80,90,100
答案 0 :(得分:3)
您的问题是对如何为数组指定值的误解
/* Commented below is your code with comments of what the code is doing */
//sets bin element to 10.
binElement = binElement + bins;
// binArray[i] is zero (by default), so all you do is set binElement back to zero.
binElement = binArray[i];
// You still have not updated the array so it prints the default int array value of zero.
System.out.println(binArray[i]);
将您的代码更改为下面发布的代码,该代码正确地将值分配给数组,并解决您的问题:)
int[] binArray = new int[100];
int bins = 10;
int numOfIterations = 100/bins;
int binElement = 0;
for (int i=0; i<numOfIterations; i++) {
binElement = binElement + bins;
binArray[i] = binElement ;
System.out.println(binArray[i]);
}
请查看下面发布的链接,了解有关如何为数组指定值的大量示例。
答案 1 :(得分:2)
因为binArray被初始化为0,所以你永远不会写任何东西。
点击这一行:binElement = binArray[i];
说出来:binArray[i] = binElement;
它会起作用。
答案 2 :(得分:0)
您必须为binArray
的元素指定值。在for
循环中执行此操作:
binElement[i] = binElement;
不是这个
binElement = binElement[i];
答案 3 :(得分:0)
将binElement = binElement[i]
更改为binElement[i] = binElement;
同时将bins
值更改为0.然后只会打印0,10..
这样的内容。否则它会像这样打印10,20,...
。
int[] binArray = new int[100];
int bins = 10;
int numOfIterations = 100/bins;
int binElement = 0;
bins = 0; // To print from 0
for (int i=0; i<numOfIterations; i++) {
binElement = binElement + bins;
binArray[i] = binElement ;
System.out.println(binArray[i]);
}