java使用气泡排序和JOptionPanes
我想对一个数组进行冒泡排序,该数组可以是具有用户值的任意数字。但第一种方法不起作用。我真的很想使用JOptionPanes,但我甚至不知道这是否是问题所在。它编译正确,但运行不正常。这是我目前的代码:
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Gates_sortingBubble{
public static void main(String[] args)throws IOException{
String amountS;
amountS = JOptionPane.showInputDialog(null, "How many numbers would you like to sort?",
"Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
int amount = Integer.parseInt(amountS);
JOptionPane.showMessageDialog (null, "Please enter " + amount + " numbers you wish to sort.",
"Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
int[] numbers = new int [amount];
for(int i = 1; i <= amount; i++){
String tempS = JOptionPane.showInputDialog("Number " + i + ": ");
int temp = Integer.parseInt(tempS);
numbers[i] = temp;
}
sort(numbers);
}
public static void sort(int[] tosort){
int[] original = tosort.clone();
int j;
boolean flag = true; //set flag to true to begin first pass
int temp; //to hold the variable
while(flag){
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < tosort.length -1; j++ ){
if ( tosort[ j ] < tosort[j+1] ){
temp = tosort[ j ]; //swap the array elements
tosort[ j ] = tosort[ j+1 ];
tosort[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
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);
}
}
# 1 楼答案
main方法中的
for
循环从1到amount
,但是数字数组的数组索引范围从0到amount-1
。所以在这个循环中,改变:致:
它会起作用的