![](/img/trans.png)
[英]I do not understand why this code won't work(new to JRadioButtons)
[英]Can't understand why this small segment of code won't work
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
您的問題是對如何為數組賦值的誤解
/* 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]);
}
查看下面發布的鏈接,以獲取有關如何為數組分配值的大量示例。
因為binArray初始化為0,所以您永遠不會向其寫入任何內容。
翻轉此行: binElement = binArray[i];
這樣說: binArray[i] = binElement;
它會工作。
您必須將值分配給binArray
元素。 在for
循環中執行此操作:
binElement[i] = binElement;
不是這個
binElement = binElement[i];
將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]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.