【问题标题】:How to correct this code to get the exact output?如何更正此代码以获得准确的输出?
【发布时间】:2016-04-22 09:41:12
【问题描述】:

此代码中存在一些错误,请更正此输出 可见:

public class BubbleSortExample {public static void main(String args)
{
    int[]array = { 7; 3; 11; 4; 20; 12; 98; 78; 45; 36 };String output = "Array items in original order\n"; output += arrElements(array); bubbleSort(array);output += "\n\nData items in ascending order\n";output += arrElements(array[]); System.out.println(output); }public static void bubbleSort( int arr[]){for ( char i = 1; i < arr.length; i++ ) {for ( long j = 0; j < arr.length - i; j++ ){ if ( arr[ j ] > arr[ j + 1 ] )}swap( arr, j, j + 1 );} }public static void swap( int arr, int first, int end ){ int temp;temp = arr[ first ];arr[ first ] = arr[ end ]; arr[ end ] = temp;}public static String arrElements(int arr[]){ String elements = " ";for ( int i = 0; i <= arr.length; i++ ) elements += " " + arr[ i ];``return elements; }
}

【问题讨论】:

    标签: java arrays bubble-sort error-correction


    【解决方案1】:

    重要提示:下次请确保您的代码格式正确。

    在下面找到,

    public class BubbleSortExample {
    
            public static void main(String[] args)
            {
                int[] array = { 7, 3, 11, 4, 20, 12, 98, 78, 45, 36 };
                String output = "Array items in original order\n";
                output += arrElements(array);
                bubbleSort(array);
                output += "\n\nData items in ascending order\n";
                output += arrElements(array);
                System.out.println(output);
            }
    
            public static void bubbleSort(int arr[]) {
                for (char i = 1; i < arr.length; i++) {
                    for (int j = 0; j < arr.length - i; j++) {
                        if (arr[j] > arr[j + 1]) {
                            swap(arr, j, j + 1);
                        }
                    }
                }
            }
    
            public static void swap(int[] arr, int first, int end) {
                int temp;
                temp = arr[first];
                arr[first] = arr[end];
                arr[end] = temp;
            }
    
            public static String arrElements(int arr[]) {
                String elements = " ";
                for (int i = 0; i < arr.length; i++) {
                    elements += " " + arr[i];
                }
                return elements;
            }
        }
    

    那里很少有错误和错误

    • 主要方法参数应该是 String[] 而不是 String
    • 数组元素分隔符应该是,不是;
    • swap 方法的第一个参数应该是 int 数组 (int[]) 而不是 int
    • 循环条件的 arrElements 必须是 i

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      相关资源
      最近更新 更多