0

I'm quite new to Java and recently I wanted to practice more. So I stumbled in this. I wanted to print out all the values in the array using Array.sort, but all I get is:1,2,3,4,5,6 instead of;22,51,67,12,98,34. Here is the code:

public static void main(String[] args) {

            int[] array;

            array =new int[6];
            array[0]=22;
            array[1]=51;
            array[2]=67;
            array[3]=12;
            array[4]=98;
            array[5]=34;

          Arrays.sort(array);

       int i;

       for (i=0; i < array.length; i++){
              array[i]= i+1;
            System.out.println("num is"+array[i]);
}
1
  • Just commenting to let you know, this is not related to netbeans. Commented May 1, 2015 at 17:09

2 Answers 2

2

You're refilling the elements in array[i] inside the for loop. Just print the contents of the array:

for (i=0; i < array.length; i++){
    //remove this line since it's setting the value of (i+1) to array[i]
    //array[i]= i+1;
    //leave this line only
    System.out.println("num is"+array[i]);
}

Or, use Arrays.toString to display the content of your array:

//no for loop needed
System.out.println("Array data: " + Arrays.toString(array));
Sign up to request clarification or add additional context in comments.

Comments

0

You could always use your own code, EG:

private void butgoActionPerformed(java.awt.event.ActionEvent evt) {                                      
    int nums[] = {13,6, 1, 25,18,12};                
    //Array is called "nums", holds random numbers and such

    int place = 0;
    int check = 0;

    while (place < nums.length - 1) {

        while (check < nums.length) {             
            // "Check" loops inside place and checks to see where larger

            if (nums[place] > nums[check]) {     
                //Change To < For Descending

                int temp = nums[place];
                nums[place] = nums[check];      
                //"Check" swaps the values around

                nums[check] = temp;

            }
            check++;

        }

        //"Place" tells loop when to stop and holds a value to be compared

        place++;
        check = place + 1;
    }

    place = 0;                              
    //"Place" acts as a counter

    while (place < nums.length) {     
        //Output Loop
        txtout.append("\n" + nums[place] + "");     
        //"txtoutput" is the textarea (.append means to add to the text already there

        place++;                             
        //"\n" means new line
    }


}   

1 Comment

This... Doesn't really answer the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.