我的代码会对数字进行正确排序,但是当它输出数组时,排序的数字会重复两次。我希望它输出原始数组,然后输出排序数组。它必须以这种方式分成不同的方法。这是我目前的代码:
import javax.swing.*;
import java.io.*;
import java.util.*;
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; //set flag to true to begin first pass
int temp; //to hold the variable
while(flag){
flag= false;
for( j=0; j < tosort.length -1; j++ ){
if ( tosort[ j ] < tosort[j+1] ){
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: " + Arrays.toString(unsorted) + ". \nYour new five numbers are: " + Arrays.toString(sorted) + ".", "Sorted Arrays", JOptionPane.INFORMATION_MESSAGE);
//Arrays.toString(sorted)
}
}
答案 0 :(得分:1)
也许你不应该输入这个:
public static void sort(int[] tosort){
int[] original = tosort;
它将复制两个数组的地址。不是它们中的价值。你可以使用for循环将每个值从一个复制到另一个。
答案 1 :(得分:1)
您可以使用:
int[] original = tosort.clone();
这会将所有元素复制到原始数组。
答案 2 :(得分:0)
好的,所以你将原始号码存储在:
int[] numbers = {number1, number2, number3, number4, number5};
没关系。现在更改sort()签名以返回带排序数组的int [],并稍微修改为:
//returns an array of sorted numbers
public static int[] sort(int[] tosort){
//create a temporary array that will be returned with sorted numbers
int[] tempArray = Arrays.copyOf(tosort, tosort.length);
int j;
boolean flag = true; //set flag to true to begin first pass
int temp; //to hold the variable
while(flag){
flag= false;
for( j=0; j < tempArray.length -1; j++ ){
if ( tempArray[ j ] < tempArray[j+1] ){
temp = tempArray[ j ];
tempArray[ j ] = tempArray[ j+1 ];
tempArray[ j+1 ] = temp;
flag = true;
}
}
}
//return our sorted array
return tempArray;
}
然后,在您的main()中,您可以执行以下操作:
//get sorted array
int[] sorted = sort(numbers);
//print sorted and original array
print(sorted, numbers);