简体   繁体   中英

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]);
    }

Keeps printing: 0 0 0 0 0 0 0 0 0 0

Trying to print: 0, 10, 20, 30, 40 ,50, 60, 70, 80, 90, 100

Your problem is a misunderstanding of how to assign a value to an array

/* 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]);

Change your code to the code posted below which correctly assigns values to an array, and your problems are solved :)

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]);
}

Take a look at the link posted below for plenty of examples on how to assign values to an array.

Arrays

Because binArray is initialized to 0, and you are never writing anything to it.

Flip this line: binElement = binArray[i]; to say this: binArray[i] = binElement; and it will work.

You have to assign values to elements of binArray . Do this within the for loop:

binElement[i] = binElement;

not this

binElement = binElement[i];

Change binElement = binElement[i] to binElement[i] = binElement; Also change the bins value to 0. Then only it will print 0,10.. like this. Otherwise it will print 10,20,... like this.

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM