0

我在使用另一个类中的方法时遇到问题。我必须调用一个方法,该方法调用另一个方法来使用冒泡排序对字符串数组进行排序。

编码:

    /**
 * My pride and joy, the bubble sort.
 * @return 
 */
public void BubbleSort(){

    boolean run = true;
    String temp;

    while (run)
    {
        run = false;

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

                if(stringArray[i].compareToIgnoreCase( stringArray[i+1]) > 0)
                {

                    temp = stringArray[i];

                    stringArray[i] = stringArray[i+1];

                    stringArray[i+1] = temp;

                    run = true;
                }// end of if
            }// end of for
    }// end of while

    System.out.println(stringArray);


}// end of BubbleSort




public void PrintSortedString(){
    BubbleSort();
}

这是两种方法。

从驱动程序类调用它时(注意方法在另一个类中)我这样称呼它

stringUtility.PrintSortedString();

输入是::

    Please enter names:
z
a
Your names:
[z, a]
[Ljava.lang.String;@4efe03b3 // this is where it should priont [a,z]

我做错什么了?

4

2 回答 2

3

你所看到的

[Ljava.lang.String;@4efe03b3

是结果

System.out.println(stringArray);

它在内部调用stringArray.toString()并打印结果。

此行为适用于所有对象。如果您想要自定义字符串消息,您需要让您的类实现自定义toString()方法,而不是依赖Object#toString(). 由于您无法更改String[]类,因此您需要自己迭代元素。

或者,您可以依赖Arrays作为 JDK 一部分的类

System.out.println(Arrays.toString(stringArray));
于 2013-09-26T02:59:09.357 回答
0

代替

System.out.println(stringArray);

尝试使用...

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

第一个是打印有关数组的信息,第二个是打印内容......

更新

如果您希望方法返回排序操作的结果,那么您需要定义方法来执行此操作...

public String[] BubbleSort(){
    /*...*/
    return stringArray;
}// end of BubbleSort

public String[] PrintSortedString(){
    return BubbleSort();
}

这将允许您使用System.out.println(Arrays.toString(stringUtility.PrintSortedString())

您还应该花时间阅读Java 编程语言的代码约定

于 2013-09-26T02:59:07.327 回答