簡體   English   中英

用戶輸入 int 到 Array 然后使用冒泡排序對數字進行排序

[英]User input int to Array then use bubble sort to sort numbers

這是我第一次在這個博客上發帖。 我是 Java 新手,當用戶輸入一組值時,我遇到了使用冒泡排序的問題。 以下是我的代碼; 但是,我正在尋找更多的建議而不是答案,因為我不會通過答案學習語言。

感謝您的幫助,如果我的代碼有點復雜,再次抱歉。 順便說一句,我剛開始學習 Java,所以我無法遵循非常復雜的編碼建議。

import java.util.Arrays;
public class bubbleSort{

    public static void main(String[] arg){

        java.util.Scanner input = new java.util.Scanner(System.in);
        System.out.println("Enter total amount of numbers:" );

        int n = input.nextInt();

        int [] numbers = new int[n];

        System.out.println("Enter the numbers: ");
        for (int i = 0; i < n; i++) {
           numbers[i] = input.nextInt();
        }

        System.out.println(list(n));

        bubbleSort(n);

        System.out.println(list(n));    
    }


    public static void bubbleSort(int[] n){

        boolean flag;

        do{

            flag = false; 

            for(int i = 0; i < n.length - 1; i++){

                if (n[i] > n[i + 1]){

                    int temp = n[i];
                    n[i] = n[i + 1];
                    n[i + 1] = temp;

                    flag = true;
                }

            }

        } while (flag);
    }
 }

當您開始引用未定義的標識符list時,您的代碼有點混亂。

我認為你需要:

System.out.println(Arrays.toString(numbers));

bubbleSort(numbers);

System.out.println(Arrays.toString(numbers)); 

代替:

System.out.println(list(n));

bubbleSort(n);

System.out.println(list(n));    

n是輸入數字的數量,而不是您想要排序的數字。 numbers包含輸入數據,並且是更合理的排序方式。

你的代碼有問題。

System.out.println(list(n));//list(n)came out of nowhere

而且您的代碼似乎只整理出其中一個數組元素。

你可以試試這個:

public class BubbleSort {
public static void main(String[] args){
    int[] myArray = new int[10];
    for(int i = 0; i < myArray.length; i++){
        myArray[i] = (int)(Math.random()* 100 + 1);
        System.out.print(myArray[i] + " ");
    }
    System.out.println();
    bubbleSort(myArray);
}
public static void bubbleSort(int[] array){
    for(int i = 0; i < array.length - 1; i++){
        for(int j = 0; j < array.length -1 - i; j++){
            if(array[j] > array[j+1]){
                int temp = array[j+1];
                array[j+1] = array[j];
                array[j] = temp;
            }
        }
    }
    for(int i = 0; i < array.length; i++){
        System.out.print(array[i] + " ");
    }
}

因此,讓我們提供有關您的代碼的更多信息。

  • 第一:使用Java 命名約定 你的BubbleSort應該是bubbleSort
  • 第二:不要創建與類同名的方法,除非它是構造函數
  • 第三:Java 是強類型的,這意味着(在您的情況下)如果您創建一個接收參數為int[] nbubbleSort(int[] n) )的方法,這意味着您只向它傳遞一個 int 數組
  • 第四:不要使用不存在的方法(例如: list(n) ,至少在你的班級上)

這些是您提供的代碼的好建議。 希望它可以幫助您更多地了解 Java 世界。

暫無
暫無

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

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