2016-04-28 172 views
0

我试图做一个读取文件并返回一个整数数组,然后将每行数据转换为整数的方法。然后,我想在使用结果数组并将它们写回文件之前使用冒泡排序对数据进行排序。我很确定我的冒泡排序代码是正确的,但是我有问题试图将整数写回到文件中...我已经复制并粘贴了我下面得到的整个代码:)将整数数组写入文件

import java.io.*; 
import java.util.Scanner; 

public class Main { 


public static void main(String[] args) throws IOException, 
    FileNotFoundException { 

String filename = "/Users/Desktop/13-2/src/pkg13/pkg2/sort.txt"; 
processFile(filename); 
writeToFile(filename);//calls method processFile 
} 


public static void processFile (String file) 
throws IOException, FileNotFoundException{ 
//String line; 
//lines is declared as a string 

String filename = "/Users/Desktop/13-2/src/pkg13/pkg2/sort.txt"; 
try (BufferedReader inputReader = new BufferedReader (new  InputStreamReader(new  FileInputStream("/Users/Desktop/writeTofile/src/writetofile/scorewrite.txt")))) { 
     String line; 
     while ((line = inputReader.readLine()) != null) { 
      double number = Double.parseDouble(line); 
     } 
//Scanner scanner = new Scanner(new File(filename)); 
//int i = 0; 
//while(scanner.hasNextInt()){ 
    // bubble[i++] = scanner.nextInt(); 

} 
} 

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

    outputWriter.println(); 


outputWriter.flush(); 
outputWriter.close(); 
} 
private int[] array = new int[25]; 

public int maxi(int[]a, int first){ 
    int max = 0; 
    for(int i=first; i<a.length; i++) 
    { 
     if (a[max]<a[i]){ 
      max =i; 
     } 
    } 
    return max; 
} 

public void bubble(double number) { 
    boolean a = false; 
    for (int i=0; i<array.length-1; i++) { 
     if (array [i]> array [i+1]) { 
      int temp = array [i]; 
      array [i] = array [i+1]; 
      array [i+1] = temp ;} 
     a= true; 

     } 
    } 
} 

回答

1

你正在编写只有一个空行到输出文件的位置:

outputWriter.println(); 

你需要从你的阵列编写所有的数字,但你甚至不把它们存储在任何地方:

double number = Double.parseDouble(line); 

在这一行之后,数字为f ROM输入文件需要存储在一个数组中。

提示片段:

int i=0; 
while ((line = inputReader.readLine()) != null) { 
     array[i++] = Integer.parseInt(line); 
    } 

你也与整数混合双打:(

你也错了,你的冒泡排序是正确的:(

我建议先从一些更加简单,只需读取整数并将其写回文件即可。