对于我的作业,我必须从一个包含 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 ();
}