2015-02-24 262 views
0

我的問題是我無法從帶有單詞列表的.txt向數組賦值。我相信問題在於我要求的東西還不可用,比如在未知的情況下要求未來的某些東西。這是我的代碼,任何幫助將與任何提示將被讚賞。Java將值賦給增加數組

File words = new File("wordList.txt"); //document with words 

String wordToArray = new String(); 
String[] arrWord = new String[3863]; // number of lines 
Scanner sc = new Scanner(words); 
Random rWord = new Random(); 
int i = 0; 


do 
{ 
    wordToArray = sc.next(); //next word 
    arrWord[i] = wordToArray; //set word to position 
    i++; //move to next cell of the array 
    sc.nextLine(); //Error occurs here 
}while(sc.hasNext()); 
+0

添加您正在收到的特定錯誤。這段代碼不起作用? – markbernard 2015-02-24 20:09:20

+0

NoSuchElementException:找不到行 – NoviceCoder 2015-02-24 20:10:06

+0

堆棧跟蹤應該有一個指向您的代碼的行號。上面代碼中的哪一行?你必須使用數組嗎? ArrayList將爲您提供幾乎無限的容量。 – markbernard 2015-02-24 20:12:01

回答

0
while(sc.hasNext()) { 
    sc.nextLine(); //This line should be first. 
    wordToArray = sc.next(); //next word 
    arrWord[i] = wordToArray; //set word to position 
    i++; //move to next cell of the array 
} 

請讓你的操作錯誤的順序。在獲取下一行之前應該會出現sc.hasNext()。

我以爲你可能會得到一個ArrayOutOfBoundsException。如果您使用不會發生的ArrayList。這是你如何使用數組列表。

String wordToArray = new String(); 
List<String> arrWord = new ArrayList<String>(); 
Scanner sc = new Scanner(words); 
Random rWord = new Random(); 
while(sc.hasNext()) { 
    sc.nextLine(); //This line should be first. 
    wordToArray = sc.next(); //next word 
    arrWord.add(wordToArray); //set word to position 
} 
int i = arrWord.size(); 
+0

謝謝!我應該得到那個......再次感謝! – NoviceCoder 2015-02-24 20:16:53

+0

請注意,此代碼將跳過文件的第一行。 – Jon 2015-02-24 20:19:50

+0

@Jon謝謝。我之前沒有使用Scanner,所以我只是重新訂購他的原始代碼。 – markbernard 2015-02-24 20:22:49

0

你問sc.nextLine()你條件sc.hasNext()之前。

首先,你應該切換do...while循環的while循環:

while(sc.hasNext()) { 
    wordToArray = sc.next(); // Reads the first word on the line. 
    ... 
    sc.nextLine(); // Reads up to the next line. 
} 

,以確保更多的數據可用試圖讀取它之前被讀取。然後,你也應該改變sc.hasNext()sc.hasNextLine(),以確保有另一行的文件中,不只是一個象徵:

while(sc.hasNextLine()) { 
    ... 
} 

的問題是,當你通過.txt文件的最後一行循環,在知道文件是否有另一行給你(.hasNextLine())之前,請求下一行(.nextLine())。

通常,最好使用while循環而不是do...while循環來避免這樣的情況。事實上,幾乎從來沒有這樣一種情況,實際上需要循環do...while