1

Were now on arrays and the job is to do a list of numbers and then it would show the descending order of those numbers.

Here's the condition: A Nested Loop and a Decisive Structure.

I wasn't able to use this code:

for (iLoop = iNumber.length - 1; iLoop >= 0; iLoop--){
            System.out.println("" + iNumber[iLoop]);

Because it wouldn't show a nested loop one nor any decisive structures.

I can't use any sort of method YET. Only the first for loop will do the loop for the array. Here's my code next:

        int iX, iY, iLoop;
        Scanner var = new Scanner(System.in);
        int[]iNumber = new int [10];
        for (int iIndex = 0; iIndex < iNumber.length; iIndex++){
            System.out.print("Enter a number: ");
            iNumber [iIndex] = var.nextInt();
        }
        for (iX = 0; iX < iNumber.length; iX++){
            for (iY = iX + 1; iY < iNumber.length; iY++){
                if (iNumber[iX] < iNumber[iY]){
                    iLoop = iNumber[iX];
                    iNumber[iX] = iNumber[iY];
                    iNumber[iY] = iLoop;
                }
            }
        System.out.println("" + iNumber);
        }
    }
}

Now, I can't now think why the output is:

[I@1909752
[I@1909752
[I@1909752
[I@1909752
[I@1909752
[I@1909752
[I@1909752
[I@1909752
[I@1909752
[I@1909752

I don't know what to do again. Someone help me, thank you in advance.

  • You are sorting your numbers correctly (although inefficiently) but you are not printing them correctly. Look up "how to print an array in Java" and move `printf` out of the loop. – Sergey Kalinichenko Sep 29 '17 at 11:10
  • I don't agree with the duplicate. It is not clear but OP need to print his array without add a loop or a method. Since this code is sorting is the opposite of a bubble sort (from the start to the end), this can be printed after each loop. – AxelH Sep 29 '17 at 11:41

2 Answers2

1

Print the iNumber[] array out of the loop :

for(int a : iNumber){
        System.out.println(a);
}
Mohit Tyagi
  • 2,788
  • 4
  • 17
  • 29
1

Since you are sorting your array by setting the smallest value first into iNumber[iX] by iterating the elements after that point iY = iX + 1. You can simply print the iNumber[iX], each inner loop will set the correct value in that position

for (iX = 0; iX < iNumber.length; iX++){
    for (iY = iX + 1; iY < iNumber.length; iY++){
        if (iNumber[iX] < iNumber[iY]){
            iLoop = iNumber[iX];
            iNumber[iX] = iNumber[iY];
            iNumber[iY] = iLoop;
        }
     }
    System.out.println("" + iNumber[iX]); //Print the actual value
}

This will nicely print every value of iNumber[iX] after the loop setting his value.

AxelH
  • 14,325
  • 2
  • 25
  • 55