gpt4 book ai didi

java - 尝试输出冒泡排序数组

转载 作者:行者123 更新时间:2023-12-02 06:26:38 24 4
gpt4 key购买 nike

我正在尝试对数组进行冒泡排序,然后输出原始数组和排序后的数组。它似乎有效,但是当它输出数据时,它输出 [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);

}


}

最佳答案

您可以在 print 方法中使用 Arrays.toString(sorted) 来获得所需的行为。

public static String toString(int[] a)

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null.

Parameters: a - the array whose string representation to return

Returns: a string representation of a

Since: 1.5

来源:http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString%28int%5B%5D%29

关于java - 尝试输出冒泡排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20455849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com