2013-10-29 29 views
0

對於作業分配,我需要創建一個可以讀取和寫入字節數組的文件的類。我已經成功創建了可以讀取和寫入CSV和文本的類,但是對於數組,我遇到了一些困難。創建二維數組然後將其寫入文件(Java)的難點

我寫了一個使用FileOutput類(創建文件,類可以在這裏找到http://www.devjavasoft.org/SecondEdition/SourceCode/Share/FileOutput.java)的方法(writeByte - 見下文)。 我陷入了嵌套for循環。我需要for循環來允許用戶輸入一系列由製表符分隔的整數。

當下面的代碼運行時我得到以下錯誤:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method writeNewline() in the type FileOutput is not applicable for the arguments (String[]) 

我明白這是什麼錯誤消息對我說,但是當我試圖創建在FileOutput新writeNewLine方法上課,我無所謂。我希望有人能夠告訴我如何解決這個問題。我非常樂意不使用FileOutput類,因爲我已經成功創建了使用它的其他文件處理程序,所以我只使用它。

親切的問候


public void writeByte(final String fileNameOUT){ 
    Scanner input = new Scanner (System.in); 
    FileOutput createData = new FileOutput (fileNameOUT); 
    System.out.println("How many rows?"); 
    int rowsOut = input.nextInt(); 
    System.out.println("How many columns?"); 
    int columnsOut = input.nextInt(); 


    System.out.println("Please enter data, separate each column with a tab."); 


     String[] dataIn; 
     int [] [] data = new int [rowsOut] [columnsOut];  
     String[] line = null; 

     for (int i = 0; i < rowsOut; i++){ 
        line = createData.writeNewline(dataIn = input.nextLine().split("\t")); 
      for (int j = 0; j < columnsOut; j++){ 
       data[i][j] = Integer.parseInt(line[j]); 
       System.out.print(data[i][j]); 

      } 
     } 
     createData.close(); 

} 
+0

你有任何特定的間距要求嗎?我不明白爲什麼你不直接寫行(因爲除非序列化內容,否則將文件寫入文件沒有什麼意義)。 – Makoto

回答

1

通過去在代碼其明確表示writeNewline沒有一個說法。我認爲你想要做的是:

for (int i = 0; i < rowsOut; i++){ 
      createData.writeNewline(); 
      String lineString = input.nextLine(); 
      line = lineString.split("\t"); 
      for (int j = 0; j < columnsOut; j++){ 
       data[i][j] = Integer.parseInt(line[j]); 
       System.out.print(data[i][j]); 
      } 
     } 
+0

謝謝,我想我快到了。在實現你的代碼之後,我得到以下錯誤。有任何想法嗎?非常感謝線程「main」中的異常java.lang.NumberFormatException:對於輸入字符串:「」 \t at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) \t at java.lang.Integer.parseInt(Integer的.java:504) \t在java.lang.Integer.parseInt(Integer.java:527) \t在com.gc01.FileManager.ByteManager.writeByte(ByteManager.java:59) \t在com.gc01.FileManager。 ByteManager.main(ByteManager.java:89) –

+0

你知道我在寫什麼......你在輸入Integer.parseInt(line [j])期待的數字;如果你傳遞字符串,它會拋出numberformatexception –

+0

我會將lineString更改爲int並接受整數嗎?如果是這樣,我將如何編寫其餘的代碼?非常感謝! –

1

我建議你使用IDE,比如Netbeans或Eclipse。語法和語義問題由IDE標記,因此您可以在編輯代碼時看到問題出在哪裏,而無需始終編譯該文件。 (我希望它作爲評論,但我不能這樣做,所以很抱歉)。

+0

我想現在你可以:-) –

+0

謝謝你,你是一個偉大的幫助:) – Aksirba