【发布时间】:2020-05-17 12:46:40
【问题描述】:
import java.util.*;
import java.io.*;
public class ReadingFiles {
private Scanner x;
public void openFile(){
try{
x = new Scanner("C:\\Users\\adamp\\Desktop\\test\\chinese.txt");
}//try
catch(Exception e){
System.out.println("could not find file");
}//catch
}//openFile()
public void readFile(){
while(x.hasNext()){
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}//while
}//readFile()
public void closeFile(){
x.close();
}//closeFile()
public static void main(String[] args){
ReadingFiles cz = new ReadingFiles();
cz.openFile();
cz.readFile();
cz.closeFile();
}//main
}//class
嘿,我正在学习 java,但我不知道为什么它总是给我一个错误 “线程“主”java.util.NoSuchElementException 中的异常”如果有人向我解释为什么会发生这种情况,我将不胜感激。
【问题讨论】:
-
您正在测试
x.hasNext(),但随后尝试从扫描仪中提取三个项目。看起来您已经到了扫描仪可用的项目少于三个的地步。如果(例如)剩下 2 个项目,x.hasNext()将返回 true,但您的第三个x.next()将抛出 NoSuchElementException。 -
new Scanner("C:\\Users\\adamp\\Desktop\\test\\chinese.txt");并没有按照你的想法去做。 -
好吧,我的文件中有 12 个项目,我正在关注教程link,所以我不知道是不是这样。也许教程已经过时或什么的。你能推荐一个关于写入文件和从文件读取的好教程吗?谢谢
-
您是否访问了问题顶部的重复链接(您可能需要重新加载此选项卡才能看到它)?它能解决你的问题吗?
-
是的,谢谢,我通过查看其他线程解决了它
标签: java