2014-10-18 56 views
0

我想要問用戶他們的文件的名稱,然後我要掃描該文件,以查看該文件中有多少索引,然後將其放入一個數組,然後從那裏進行。如何向用戶詢問輸入文件名,然後使用該文件名?

這裏是我的代碼:

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

public class TestScoresAndSummaryStatistics { 
    public static void main(String[] args) throws IOException { 
     int scores; 
     int indices = -1; 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("Enter the name of the file"); 
     String fileName = keyboard.next(); 

     //I believe something is wrong here, am I incorrectly bring inputFile into new File? 
     File inputFile = new File(fileName); 
     Scanner data = new Scanner(inputFile); 

     while (data.hasNext()) { 
      indices++; 
     } 
     System.out.println("There are: " + indices + "indices."); 
    } 
} 

我相信出事了與= new File(filename);部分:也許是因爲我沒有報價,但我不能完全肯定。我怎樣才能解決這個問題?

+0

你遇到了什麼錯誤? – APerson 2014-10-18 23:32:15

+0

你的錯誤可能是'keyboard.next()'調用;嘗試將其改爲'keyboard.nextLine();'。 – Pokechu22 2014-10-18 23:33:07

+1

我不明白C++部分,那是什麼? – Lrrr 2014-10-18 23:33:35

回答

0

解決方法:

變化

while (data.hasNext()) { 
    indices++; 
} 

while (data.hasNext()) { 
    indices++; 
    data.next(); 
} 

說明:

你想增加indices的每一行。要做到這一點,你應該去下一行,並檢查是否有其他可用的線路。 問:你怎麼去下一行? A:data.next();

例如, - file.txt的:

你的方法 - 壞

  • 步驟1

    line a <--- here you are 
    line b 
    line c 
    
  • 步驟2

    line a <--- here you are 
    line b 
    line c 
    

...

data.hasNext()將爲真永遠因爲你會在每一步的第一行=>無限循環

正確的做法:

  • 步驟1

    line a <--- here you are 
    line b 
    line c 
    
  • 步驟2

    line a 
    line b <--- here you are 
    line c 
    
  • 步驟3

    line a 
    line b 
    line c <--- here you are 
    

在這種情況下data.hasNext()將返回true只有3次,那麼它將返回false(該文件不具有3號線之後的任何行)

+0

我保留int indices = -1,因爲我不想在文件中包含第一個數字,因爲這是假設表示文件中有多少個數字。雖然我確實添加了data.next();它的工作,你會介意告訴爲什麼工作,我只是想了解更多,如果你不介意。 – Overclock 2014-10-18 23:44:36

+0

我建議使用indices = 0,因爲我認爲你試圖計數指數,0也是可數的。好的,我將編輯帖子以添加一些細節。 – 2014-10-18 23:47:46

0

你只檢查是否有數據在Scanner但你永遠不會消耗它。

java.util.Scanner.hasNext()方法如果此掃描器在其輸入中有另一個標記,則返回true。此方法可能會在等待輸入進行掃描時阻塞。掃描儀不會超過任何輸入。

如果文件中有任何數據,那麼下面的代碼將永遠不會結束,您無需讀取數據即可增加計數器。

while (data.hasNext()) { 
     indices++; 
    } 
+0

不知道你得到什麼,我將如何「消費」它?我不是已經將它存儲到可變數據中嗎? – Overclock 2014-10-18 23:37:43

+0

我不知道該如何更簡單。你檢查是否有數據要讀取,而你從來沒有讀過它。你認爲你在哪裏存儲它? – luk32 2014-10-18 23:38:48

+0

所以你談論我的while循環需要改變? – Overclock 2014-10-18 23:40:24

相關問題