我正在尝试对数组进行冒泡排序,然后输出原始数据和已排序数据。它似乎工作,但当它输出数据时,它输出[l @ 486f03ec作为两个数组而不是数字。我不知道我做错了什么。我的代码是
import javax.swing.*;
import java.io.*;
public class Gates_sortingBubble{
public static void main(String[] args)throws IOException{
JOptionPane.showMessageDialog (null, "Please enter five numbers.", "Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
String number1s;
number1s = JOptionPane.showInputDialog("Number 1: ");
int number1 = Integer.parseInt(number1s);
String number2s;
number2s = JOptionPane.showInputDialog("Number 2: ");
int number2 = Integer.parseInt(number2s);
String number3s;
number3s = JOptionPane.showInputDialog("Number 3: ");
int number3 = Integer.parseInt(number3s);
String number4s;
number4s = JOptionPane.showInputDialog("Number 4: ");
int number4 = Integer.parseInt(number4s);
String number5s;
number5s = JOptionPane.showInputDialog("Number 5: ");
int number5 = Integer.parseInt(number5s);
int[] numbers = {number1, number2, number3, number4, number5};
sort(numbers);
}
public static void sort(int[] tosort){
int[] original = tosort;
int j;
boolean flag = true;
int temp;
while(flag){
flag= false;
for( j=0; j < tosort.length -1; j++ ){
if ( tosort[ j ] < tosort[j+1] ){ // change to > for ascending sort
temp = tosort[ j ];
tosort[ j ] = tosort[ j+1 ];
tosort[ j+1 ] = temp;
flag = true;
}
}
}
print(tosort, original);
}
public static void print(int[] sorted, int[] unsorted){
JOptionPane.showMessageDialog (null, "Your original five numbers are: [" + unsorted + "]. \nYour new five numbers are: [" + sorted + "].", "Sorted Arrays", JOptionPane.INFORMATION_MESSAGE);
}
}
答案 0 :(得分:1)
您可以在Arrays.toString(sorted)
方法中使用print
来获得所需的行为。
public static String toString(int [] a)
返回指定数组内容的字符串表示形式。字符串表示由数组元素的列表组成,用方括号括起来(“[]”)。相邻元素由字符“,”(逗号后跟空格)分隔。通过String.valueOf(int)将元素转换为字符串。如果a为null,则返回“null”。
参数: a - 返回其字符串表示的数组
返回:
的字符串表示形式自: 1.5
来源:http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString%28int%5B%5D%29
答案 1 :(得分:1)
您需要在Arrays.toString
中使用java.util
。