Java - 从文本文件中读取不同行上的单词 [英] Java - read words on different lines from a text file
问题描述
您好,请告诉我这是否是我正在使用的正确代码。假设我有一个文本文件,单独的行上有单词和提示:
1个单词
提示第一个单词
2个单词
暗示第二个单词......依此类推
我想在不同的行上为用户显示一个单词和提示。我可以用这个:
ArrayList< string> ;; words = new ArrayList< string>();
ArrayList< string> ;; hints = new ArrayList< string>();
尝试{
文件f =新文件(filename.txt);
扫描仪fSc =新扫描仪(f);
while(fSc.hasNextLine()){
String line = input.readLine();
char [] words = line.split();
words.add(str [0]);
hints.add(str [1]);
}
fSc.close();
} catch(Exception ex)
{
System.out.println(ex);
}
谢谢!
Hello, please let me know if that's the right code I am working with. Assume I have a text file with words and hints on separate lines:
1 word
hint for the first word
2 word
hint for the second word ...and so on
I want to display a word and a hint for the user on different lines. Can I use this:
ArrayList<string>; words = new ArrayList<string>();
ArrayList<string>; hints = new ArrayList<string>();
try{
File f = new File("filename.txt");
Scanner fSc = new Scanner(f);
while (fSc.hasNextLine()) {
String line = input.readLine();
char [] words = line.split();
words.add(str[0]);
hints.add(str[1]);
}
fSc.close();
}catch(Exception ex)
{
System.out.println(ex);
}
Thank you!
推荐答案
ArrayList; words = new ArrayList();
在 ArrayList <之后删除分号/ code>。
Remove the semi-colon after ArrayList
.
while (fSc.hasNextLine()) {
String line = input.readLine();
char [] words = line.split();
words.add(str[0]);
hints.add(str[1]);
}
这看起来不对。您为行拆分使用名称 words
,但随后添加 str
。您还将错误的项添加到数组中。它应该是这样的:
That does not look right. You use the name words
for your line split, but then add str
. You are also adding the wrong items into your arrays. It should be something like:
while (fSc.hasNextLine()) {
String line = input.readLine();
String[] str = line.split();
words.add(str[1]);
String line = input.readLine();
hints.add(line);
}
将来在发布问题之前总是值得编译和测试你的代码。
In future it is always worth compiling and testing your code before posting your question.
这篇关于Java - 从文本文件中读取不同行上的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!