对于我的作业,我必须从一个包含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 ();
}
答案 0 :(得分: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();
答案 1 :(得分:0)
您可以使用Arrays.sort(数字),然后将此整数数组(数字)作为writeToFile方法的参数之一传递,而不是使用用于对整数数组进行排序的swapIndex(数字),迭代这些整数元素数组(数字)并可以添加到文件中。