The problems with your code are as follows::
You’ll never get into that loop:
for(int i=n;i>vetor.length;i--) {
At the beginning, i
vale n
, which is equal to vetor.length
; when the condition is tested, it will false
face, so that it will return the vector unchanged.
And how in Java an array is always started with everything zero (or null
, if it’s a reference vector) then that’s what you’ll get.
One solution is to travel from n
until 1
:
for(int i=n;i>0;i--) {
The aux
is being set inside the body of the loop
for(int i=n;i>vetor.length;i--) {
int aux=0;
This means that even if your first problem is solved, it will always be zero. This would cause you to assign the zero position of your vector several times (one overwriting the other). The result would be something like:
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
To solve this, just move the aux
out of the loop, so that it preserves its value (incremented by you) between one iteration and another:
int aux=0;
for(int i=n;i>vetor.length;i--) {
Complete code:
int[]vetor = new int[n];
int aux=0;
for(int i=n;i>0;i--) {
vetor[aux]=i;
aux++;
}
return vetor;
Note: I’m assuming you want values 1
to n
. If you want another interval - for example 0
to n-1
- adjust the condition of your for
accordingly.