2015-11-18 33 views
-1

我需要在java中使用Scanner來讀取以下txt.file。這個文件的問題是有很多我不需要的信息。我需要的唯一的東西是參數和這些參數的值(例如,我需要String n和int 5,String p和double 0.5,String lambda和double 0.3 ...),問題似乎是在空行中。我添加了我創建的代碼,但是如果我運行此代碼,分配的第二行永遠不會被讀取。使用掃描儀讀取文件時遇到問題並跳過行

我在做什麼錯?

的txt文件作爲輸入:

distributie lengte klasse 1 naam verdeling parameter(s) value of parameter 
         n  5 
         p  0.5 
distributie lengte klasse 2 naam verdeling parameter(s) value of parameter 
         lambda  0.3 

distributie incidentie klasse 1 naam verdeling parameter(s) value of parameter 
         d  1 

distributie incidentie klasse 2 naam verdeling parameter(s) value of parameter 
         n  8 
         p  0.1  
distributie servertijd klasse 1 naam verdeling parameter(s) value of parameter 
         d  1 

distributie servertijd klasse 2 naam verdeling parameter(s) value of parameter 
         p  0.3 

aantal pakketten te verwerken     2000000 

代碼

for(int a = 0; a< 6; ++a){ 

inputStream.nextLine(); 
System.out.print("\n"+inputStream.next()); 
System.out.print("\n"+inputStream.next()); 
String line = ""; 
if (!(line = inputStream.nextLine()).isEmpty()) 
    { 
    System.out.print("\n"+inputStream.next()); 
    System.out.print("\n"+inputStream.next()); 
    } 
else 
{ 

} 
inputStream.nextLine(); 
}} 
+0

的可能的複製[跳躍nextLine()後

try (BufferedReader in = new BufferedReader(new FileReader(file))) { Pattern p = Pattern.compile("\\s+(\\w+)\\s+([0-9.]+)\\s*"); for (String line; (line = in.readLine()) != null;) { Matcher m = p.matcher(line); if (m.matches()) { String keyword = m.group(1); double number = Double.parseDouble(m.group(2)); System.out.println(keyword + " = " + number); } } } 
使用next(),nextInt()或其他nextFoo()方法](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – thegauravmahawar

+0

Just提示:你不需要'else {}'。如果你沒有在'if'的'else'部分做任何事情,你可以避免放置它。 –

回答

0

簡短的回答:不要使用Scanner

你說你「想用掃描儀方法閱讀下面的txt.file」,但你沒有說明原因,而且我們並不總是得到我們喜歡的東西。在這種情況下,使用Scanner遠非最佳選擇。

查看文件,格式似乎是以3行爲單位的數據,第一行以字distributie開頭。在文件末尾有一個以aantal開頭的摘要行。

每個塊的第2行和第3行可以是關鍵字+十進制數,也可以是空行。既然你只有那些關鍵字+數字對後的,我建議使用正則表達式讀取文件中的行由行和匹配的關鍵字+號線:

+0

感謝您的幫助,我從來沒有使用過正則表達式,但我會試一試......如果我使用它,只會找到一個關鍵字和數字。我是否必須創建另一個循環以使其遍歷整個txt.file? – StudentX

+0

對不起,模式的最後一個字符應該是'*',而不是'+'。 – Andreas

0

這裏有一些改進:

  • 對於環頭,我會使用a++遞增a - 只是偏好。
  • .nextLine()返回String,因此可能在執行.nextLine()後重置inputStream變量。
  • 打印inputStream.nextLine()而不是inputStream.next()
  • if有條件我不會初始化變量line
  • if else條件不需要在那裏做你想要的,即讀取這六個值。

我的建議是閱讀了有關REGEX,如果該行的REGEX匹配n,p,lamda,d和另一個值,然後打印。

for(int a = 0; a< 6; a++){ 
    inputStream.nextLine(); 
    //possibly reset inputStream here with something like inputStream = new Scanner(...); 
    System.out.print("\n"+inputStream.nextLine()); 
    System.out.print("\n"+inputStream.nextLine()); 
}