[英]No Such Element Exception when using Scanner
I am attempting to read a txt file. 我正在尝试读取txt文件。 I keep getting a "no such element" error and I cannot understand why.
我一直收到“没有这样的元素”错误,我不明白为什么。 My code is,
我的代码是
File myFile = new File(input.txt)
Scanner reader = new Scanner(myFile);
for (int i = 0; i<20; i++)
{
name[i] = reader.nextLine();
grade[i] = reader.nextInt();
reader.nextLine();
rank[i] = reader.nextInt();
reader.nextLine();
}
reader.close();
Here is an example of the file format . 这是文件格式的示例 。 What am I missing?
我想念什么?
This is why using a for
loop is a bad idea when reading from a file; 这就是为什么在读取文件时使用
for
循环是个坏主意的原因。 you don't know (rather, you shouldn't care for most intents and purposes) how large your file is. 您不知道文件的大小(相反,大多数情况下您都不应该理会)。
Switch it out for a while
loop: 将其切换出
while
循环:
while(reader.hasNext()) {
// code
}
(Don't forget to advance i
in the loop.) (不要忘了让
i
前进。)
Provided that your tokens are divided up into exact multiples of three, this will read the tokens in without running out of stuff to read from. 假设您的令牌被分为三个的精确倍数,这将读入令牌而不会用完所有要读取的内容。
Definitely not a good choice to use for
loop. 绝对不是使用
for
循环的好选择。
You can try something like this: 您可以尝试如下操作:
int i=0;
int i1=0;
int i2=0;
int i3=0;
while(reader.hasNextLine()) {
i++;
if(i==1){
name[i1]=reader.nextLine();
i1++;
}
if(i==2){
grade[i2]=Integer.valueOf(reader.nextLine());
i2++;
}
if(i==3){
rank[i3]=Integer.valueOf(reader.nextLine());
i3++;
i=0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.