2012-03-08 29 views
-1
private Scanner inputFile; 
private String corpusFileString = ""; 
try 
{ 
    File file = new File(sourceFile.getText()); 
    inputFile = new Scanner(file); 
    JOptionPane.showMessageDialog(null, "The file was found."); 
    if (text != null) 
    { 
     translate.setEnabled(true); 
    } 
} 
catch (FileNotFoundException ex) 
{ 
    JOptionPane.showMessageDialog(null, "The file was not found."); 
} 

try 
{ 
    numberWords = inputFile.nextInt(); 
} 
catch (InputMismatchException ex) 
{ 
    JOptionPane.showMessageDialog(null, "The first line on the file must be an integer"); 
} 

while (inputFile.hasNext()) 
{ 
    corpusFileString = corpusFileString + inputFile.nextLine() + " "; 
} 

所以當我讀這個文件時,第一行應該是一個整數(一個不同的變量可以保存),否則會拋出一個異常。 該文件的其餘部分應該是數據(所有數據的另一個變量),但由於某種原因,字符串在開始處包含空白區域,並且在分割它時,我必須在數組中使用+1來引起該空白區域。閱讀文件時的空白區域java

+3

這看起來更像是比Java C#。 – jrummell 2012-03-08 21:21:37

+0

這似乎不是相關的代碼部分。向我們展示'Scanner'類的代碼。 – 2012-03-08 21:51:31

+0

@ OlivierJacot-Descombes掃描儀是一個內置的Java類。 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html – 2012-03-08 22:15:04

回答

0

問題是它讀取第一個int,然後是第一行的其餘部分。

基本上是:

15 \ n此行\ n這裏

另一行,其中\ n是一個換行符。

它讀取15,然後它讀取到\ n,它是「」(省略換行符)。剩下的就是你所期望的。

嘗試使用:

numberWords = Integer.parseInt(inputFile.nextLine()); 

而不是

numberWords = inputFile.nextInt(); 
0

我不知道關於Java。在嘗試使用nextInt()閱讀之前,可能需要撥打hasNext()。這就是.NET讀者和統計員的工作方式。在C#中我會寫類似

while (reader.MoveNext()) { 
    string s = reader.Current; 
} 

你的情況,你可以嘗試

if (inputFile.hasNext()) { 
    numberWords = inputFile.nextInt(); 
}