java 随机取出定义数组中的元素且不重复  然后把取出的元素排序 在输出为TXT文本文件 int[] data = {40, 45, 3, 22, 5, 41, 7, 12, 9} 从上面的数组中取2个元素  不能重复取 比如取了 3,41  然后对3,41排序 在输出为TXT文件到磁盘。 要求java 源码  并且有详细注释 非常感谢 
在线等!!!!!!!!!!!!!!! 
对不起现在没有分  望高手指教!

解决方案 »

  1.   


    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Random;public class CHOOSE {
    public static void main(String args[]) throws IOException {
    saveToTXT("D:\\test.txt", choose(new int[] { 40, 45, 3, 22, 5, 41, 7,
    12, 9 }));
    } /*
     * 使用随机数从数组中选取两个数
     */
    public static String choose(int[] arr) {
    int first;// 存放第一个数的index
    int end;// 存放第二个数的index
    Random random = new Random();
    // 获取两个随机数,当两数相等时重新获取,直至不等
    do {
    // random.nextInt(int n)方法返回一个小于n的非负整数
    first = random.nextInt(arr.length + 1);
    end = random.nextInt(arr.length + 1);
    } while (first == end);
    // 将从中数组中取得的两个值以字符串形式返回,中间以空格(可修改)间隔
    // (a>b ? a:b) 返回a、b中较大的数
    return (arr[first] > arr[end] ? arr[end] : arr[first]) + " "
    + (arr[first] < arr[end] ? arr[end] : arr[first]);
    } /*
     * 以FileWriter将取得的值保存到TXT文件中
     */
    public static void saveToTXT(String path, String content)
    throws IOException {
    File file = new File(path);
    // 判断文件是否以存在,若不存在则新建之
    if (!file.exists())
    file.createNewFile();
    FileWriter fw = new FileWriter(file, true);
    fw.write(content);
    fw.close();
    }
    }
      

  2.   

    非常感谢jcyan
      

  3.   

    非常感谢jcyan
      

  4.   


    import java.util.*;
    import java.io.*;
    public class RandomTxt {    public static void main(String[] args) {
            int[] data1 = {3, 5, 6, 8, 9, 15, 18, 24, 27, 30, 32};
            Random r = new Random();
            int[] data2 = new int[7];
            int irdm = 0;
            for(int i = 0; i < 7; i ++) {
                irdm = r.nextInt(11 - i);
                data2[i] = data1[irdm];
                System.out.print(data1[irdm]+" ");
                for(int j = irdm; j < 11 - i - 1; j ++) {
                    data1[j] = data1[j + 1];
                }
            }
            sort(data2);
            System.out.println();
            for(int i=0;i<data2.length;i++){
             System.out.print(data2[i]+" ");
            }
    try {
    FileWriter fw = new FileWriter("F:/coderone.txt");
    BufferedWriter bw = new BufferedWriter(fw);

    for (int i = 0; i < data2.length; i++) {
     bw.write(String.valueOf(data2[i])+" ");

     
    bw.close();
    fw.close();
    } catch (Exception e) {
    // TODO: handle exception
    }        
        } private static void sort(int[] data2) {
    // TODO Auto-generated method stub
    int k ;
    int temp=0 ;
    for(int i=0;i<data2.length;i++){
    k = i ;
    for(int j=k+1;j<data2.length;j++){
    if(data2[i]>data2[j]){
    temp = data2[i];
    data2[i] = data2[j];
    data2[j] = temp ;
    }
    }
    }
    }
    }
      

  5.   

    非常感谢coderone
    此程序比较灵活!