1

对于我的作业,我必须从一个包含 25 个数字的文件中读取,然后按顺序对其进行排序,然后将其写入另一个文件。我想不出一种方法在我的代码中传递数组(到数组的字符串)以按顺序写入文件并将数字写入不同的文件。
这可能是一个简单的问题,但我只是在尝试通过所有内容时遇到了一点麻烦。先感谢您。

public static void main(String[] args) throws IOException{
    int[] number;
    number = processFile ("Destination not specified");
    swapIndex(number);
    writeToFile ("Destination not specified");

}

public static int[] processFile (String filename) throws IOException, FileNotFoundException{

    BufferedReader inputReader = new BufferedReader (new InputStreamReader(new FileInputStream(filename)));

    String line;
    int i = 0;
    int[] value = new int [25];
    while ( (line = inputReader.readLine()) != null){
    int num = Integer.parseInt (line);      // Convert string to integer.
           value[i] = num;    
            i++;
            System.out.println (num); // Test 
    }
    inputReader.close (); 
    return value;
    // Read the 25 numbers and return it
}

public static void swapIndex (int[] num){   // BUBBLE sort
    boolean order = true;
    int temp;

    while (order){
        order = false; 
        for (int i = 0; i <num.length-1; i++){
            if (num[i]> num[i+1]){
                temp = num[i]; //set index to temp
                num[i] = num [i+1]; // swap
                num[i+1]= temp; //set index to the higher number before it
                order = true;
            }
        }
    }          
} // Method swapIndex

public static void writeToFile (String filename) throws IOException {
    BufferedWriter outputWriter = new BufferedWriter(new FileWriter(filename));

       outputWriter.write (String.valueOf ()); // Need to take the string value of the array
       outputWriter.flush(); 
       outputWriter.newLine ();
}
4

2 回答 2

1

我会这样做

    Set<Integer> set = new TreeSet<Integer>();
    Scanner sc = new Scanner(new File("1.txt"));
    while (sc.hasNextInt()) {
        System.out.println(sc.nextInt());
    }
    sc.close();
    PrintWriter pw = new PrintWriter(new File("2.txt"));
    for (int i : set) {
        pw.println(i);
    }
    pw.close();
于 2013-04-28T05:05:27.430 回答
0

您可以使用 Arrays.sort(number) 代替用于对整数数组进行排序的 swapIndex(number),然后将此整数数组(number)作为参数之一传递给 writeToFile 方法,迭代整数数组(number ) 并且可以添加到文件中。

于 2013-04-28T03:35:20.720 回答