日期:2014-05-20  浏览次数:20825 次

关于升降排序问题
有没有大神能帮小弟解决一下难题!首先输入5个数字,然后按1顺序排列,按2降序排列!

------解决方案--------------------
import java.util.Arrays;
import java.util.Scanner;

public class SortTest {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入5个数");
double[] array = new double[5];
int count = 0;
double number = 0;
while(count < 5){
number = sc.nextDouble();
array[count] = number;
count++;
}

System.out.println("然后输入1升序排列,2降序排列");
while(true){
number = sc.nextDouble();
if(number == 1){
Arrays.sort(array);
break;
}
else if(number == 2){
Arrays.sort(array);
for(int i = 0; i < array.length/2; i++){
double temp = 0;
temp = array[i];
array[i] = array[array.length - i];
array[array.length - i] = temp;
}
break;
}
System.out.println("请输入1升序排列,2降序排列");
}

for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
}
System.out.println();
}

}

------解决方案--------------------
Java code
import java.util.*;

public class Demo_5 {
    public static void main(String[] args) throws Exception{
        Scanner sc = new Scanner(System.in);
        double[] arr = new double[5];
        
        System.out.println("请输入五个数字");
        for (int i=0; i<5; i++){
            double number = sc.nextDouble();
            arr[i] = number;
        }
        //测试输入的五个数字是否正确
        //for (double e: arr)
            //System.out.println(e);
        while (true){
            String str = javax.swing.JOptionPane.showInputDialog(" 1: 升序  2: 降序");
            int j =(int)Integer.parseInt(str);
            switch(j){
            //升序
            case 1: {
                Arrays.sort(arr);
                for (double e: arr)
                    System.out.print(e + " ");
                System.out.println();
            }break;
            //降序
            case 2:{
                for (int k=arr.length-1; k>=0; k--)
                    System.out.print(arr[k] + " ");
                System.out.println();
            }break;
            default :{
                javax.swing.JOptionPane.showMessageDialog(null, "你的输入有误!!!");
            }break;
            }
        }

    }
}