簡體   English   中英

我在NetBeans中使用的array.sort沒有排序

[英]My array.sort that I'm using in netbeans, isn't sorting

我是Java的新手,最近我想練習更多。 所以我偶然發現了這個。 我想使用Array.sort打印出數組中的所有值,但是我得到的只是: 1,2,3,4,5,6而不是; 22,51,67,12,98,34 這是代碼:

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

您要在for循環內重新填充array[i]的元素。 只需打印數組的內容:

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

或者,使用Arrays.toString顯示數組的內容:

//no for loop needed
System.out.println("Array data: " + Arrays.toString(array));

您始終可以使用自己的代碼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
    }


}   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM