I suggest you step through the code in your debugger as debugging programs is what it is for.
What I would expect you would see is that every time the code loops int x = 0;
is set.
You always set x
to 0
before changing array's value.
You can use:
int[] tall = new int[28123];
for (int j = 0;j<28123;j++){
// Or whatever value you want to set.
tall[j] = j + 1;
}
Or just remove the initialization of x (int x=0
) before the for loop.
put x=0 outside the for loop that is the problem
No, you're re-initializing x
in every loop. Change to:
int[] tall = new int[28123];
int x = 0;
for (int j = 1;j<=28123;j++){
tall[x] = j;
x++;
}
Or, even better (since x
is always equal to j-1
):
int[] tall = new int[28123];
for (int j = 1;j<=28123;j++){
tall[j-1] = j;
}
You have not one, but many mistakes. It should be:
int[] tall = new int[28123];
for (int j=0;j<28123;j++){
tall[j] = j+1;
}
Your code is putting a 0 in all the positions of the array.
Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).
public class Array {
static int a[] = new int[101];
int counter = 0;
public int add(int num) {
if (num <= 100) {
Array.a[this.counter] = num;
System.out.println(a[this.counter]);
this.counter++;
return add(num + 1);
}
return 0;
}
public static void main(String[] args) {
Array c = new Array();
c.add(1);
}
}
Source: Stackoverflow.com