简体   繁体   English

为什么我的气泡排序代码会打印出这些奇怪的东西?

[英]Why is my bubble sort code printing out this weird stuff?

Ok, so here's my code. 好的,这是我的代码。 I think it should work fine to sort those numbers in the array. 我认为对数组中的这些数字进行排序应该很好。 However, every time I attempt to run it, all it does is print "[I@178af9c0" or some weird variation on that. 但是,每次我尝试运行它时,它所做的只是打印“ [I @ 178af9c0””或一些奇怪的变化。 I have absolutely no idea what do about this and would appreciate any help that you can give me. 我完全不知道该怎么办,希望您能给我任何帮助。 Thank you very much!!! 非常感谢你!!!

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

In Java, arrays are classes. 在Java中,数组是类。 So that string is the reference to the array, not the contents of the array. 因此,该字符串是对数组的引用,而不是数组的内容。 If you want to print the contents, probably the easiest way is to iterate over all the elements. 如果要打印内容,最简单的方法可能是遍历所有元素。

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

(Tested on Java 8, twiddle for your version of Java.) (在Java 8上进行了测试,为您使用的Java版本作了测试。)

There are some logic errors in there, but as this looks like a homework question, I'll just mention that you are heading down the right lines, but may need to pencil out what you're actually doing and draw the flow. 那里存在一些逻辑错误,但是由于这看起来像是一个作业问题,我只想提一下您正在正确的路线上,但可能需要指出您实际在做什么并绘制流程。

要获取数组的String表示形式,可以使用Arrays.toString(yourArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM