簡體   English   中英

將用戶輸入從高到低排序會在 Java 中給出錯誤答案

[英]Sorting a user input from High to low gives wrong answer in java

下面是我的程序,它接受用戶輸入,然后將其從高到低排序:

該程序將用戶的輸入作為Integer ,然后將其轉換為string ,然后將其傳遞給sort(int[] sort)方法。

public class SortLtoS { 

void convert(int n)                     // converts int to string
{
    String temp = Integer.toString(n);
    int [] sort = new int[temp.length()];
    for(int i=0;i<temp.length();i++)
    {
        sort[i] = temp.charAt(i)-0; 

    }

    sort(sort);
}
void sort(int[] sort)           // bubble sort the integer array
{

    int temp=0;         
    for(int j=0;j<sort.length;j++)
    {
        for(int k=1;k<(sort.length-j);k++)
        {
            if(sort[k-1]>sort[k])
                temp=sort[k-1];
            sort[k-1]=sort[k];
            sort[k]=temp;
        }

        for(int i=sort.length-1;i>=0;i--)
            System.out.println(sort[i]);
    }


}


public static void main(String[] args) {

    System.out.println("Enter the number to sort");
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    SortLtoS t = new SortLtoS();
    t.convert(a);


  }

 }

現在,當我提供輸入為 76878 時,它應該給出輸出為 88776 但它給出的輸出為

55 56 55 56 54 55 55 56 55 56 55 55 56 56 55 55 55 56 56 56 55 55 56 56 56

我在這里做錯了什么?

你想要的不是sort[i] = temp.charAt(i)-0; ,應該是sort[i] = temp.charAt(i)-'0'; ,你想減去字符'0'的編碼,而不是0的值。雖然我認為你不需要這一步,因為最初從你的main方法中,你可以只掃描一個字符串,你為什么要掃描一個int,並將其轉換為字符串? 只是為了確保它是一個有效的數字?

你代碼的另一個問題是,你應該用if語句的花括號括起交換邏輯的所有三個語句。 將數組sort打印語句移出排序邏輯。

你的sort函數應該是這樣的:

void sort(int[] sort) // bubble sort the integer array
{
    int temp = 0;
    for (int j = 0; j < sort.length; j++) {
        for (int k = 1; k < (sort.length - j); k++) {
            if (sort[k - 1] > sort[k]) {
                temp = sort[k - 1];
                sort[k - 1] = sort[k];
                sort[k] = temp;
            }
        }
    }

    for (int i = sort.length - 1; i >= 0; i--)
        System.out.println(sort[i]);

}

它通過使用集合框架來工作

public class SortLtoS  {

    public static void main(String[] args) {
        System.out.println("Enter the number to sort");
        Scanner sc = new Scanner(System.in);
        Integer number  = sc.nextInt();
        List<String> list = new ArrayList<String>();
        Integer rem;
        Integer n = 0;
        do {
            rem = number % 10;
            number = number / 10;

            list.add(rem.toString());
        } while (number > 0);

        Comparator comparator = Collections.reverseOrder();
        Collections.sort(list, comparator);
        String[] str = new String[list.size()];
        str = list.toArray(str);
        StringBuilder builder = new StringBuilder();

        for (String s : str) {
            builder.append(s);
        }
        System.out.println(builder.toString());
    }
}

暫無
暫無

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

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