I'm attempting to bubble sort an array, then output the original and the sorted. It seems to work, but when it outputs the data, it outputs [l@486f03ec as both arrays instead of numbers. I don't know what I did wrong. My code is
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);
}
}
You can use Arrays.toString(sorted)
in the print
method to get the desired behaviour.
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
Source: http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString%28int%5B%5D%29