2016-04-28 116 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); 
    } 

你也與整數混合雙打:(

你也錯了,你的冒泡排序是正確的:(

我建議先從一些更加簡單,只需讀取整數並將其寫回文件即可。