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

Instead of swapIndex(number) you used to sort the integer array, you could use Arrays.sort(number) and then pass this integer array(number) as one of the arguments to writeToFile method, iterate over those elements of integer array(number) and can add to the file.

于 2013-04-28T03:35:20.720 に答える