2015-02-24 169 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