【问题标题】:Why is my bubble sort code printing out this weird stuff?为什么我的冒泡排序代码会打印出这些奇怪的东西?
【发布时间】:2015-11-22 20:20:59
【问题描述】:

好的,这是我的代码。我认为对数组中的这些数字进行排序应该可以正常工作。但是,每次我尝试运行它时,它所做的只是打印“[I@178af9c0”或一些奇怪的变化。我完全不知道该怎么做,如果你能给我任何帮助,我将不胜感激。非常感谢!!!

public class BubbleSort {



    public void Print(){

    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        int[] BubbleSort = {3, 4, 1, 2};    
            int lengthOfArray = BubbleSort.length;

            for (int i = 0; i < lengthOfArray - 1; i++){
                for (int n = 1; n < lengthOfArray - i; n++){
                    if (BubbleSort[n - 1] > BubbleSort[n]){
                         Swap(i, n , BubbleSort);
                    }
                }
            }
            System.out.println(BubbleSort.toString());  
    }



     private static void Swap(int index1, int index2, int[] array) {       
         int temp;
         temp = array[index1];
         array[index1] = array[index2];
         array[index2] = temp;
     }
}

【问题讨论】:

  • 另外,我的代码有什么明显的问题吗?
  • 您正在尝试打印数组 System.out.println(BubbleSort.toString());您实际上应该打印数组中包含的项目 for(i=0;i

标签: java arrays sorting printing


【解决方案1】:

在 Java 中,数组是类。所以该字符串是对数组的引用,而不是数组的内容。如果要打印内容,可能最简单的方法是遍历所有元素。

for(int  i : BubbleSort)  System.out.println(""+i);

(已在 Java 8 上测试,适合您的 Java 版本。)

那里有一些逻辑错误,但由于这看起来像是一个家庭作业问题,我只想提一下你正在朝着正确的方向前进,但可能需要用铅笔画出你实际在做什么并画出流程.

【讨论】:

    【解决方案2】:

    要获取数组的字符串表示,可以使用Arrays.toString(yourArray);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-07
      • 2011-02-17
      • 2011-03-17
      • 2016-03-07
      • 2017-06-28
      • 2016-06-09
      • 2016-01-29
      • 1970-01-01
      相关资源
      最近更新 更多