[英]Why am I receiving a NoSuchElementException?
我最近开始学习FileIO,并创建了一个简单的程序,用户可以输入其名称和年龄。 该程序编译正常,但是当我运行该程序时,出现以下消息:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at FileIO.main(FileIO.java:18)
我不确定此编译器错误的含义,如果有人可以向我解释它,我将不胜感激。 谢谢!
import java.util.*;
import java.io.*;
public class FileIO
{
public static void main( String args[] )
{
String sourceFile = "inputfile.txt";
String destinationFile = "outputfile.txt";
try{
File sfile = new File(sourceFile);
Scanner input = new Scanner(sfile);
while(input.hasNext())
{
String fname = input.next();
String lname = input.next();
int age = input.nextInt();
System.out.println(fname + ' ' + lname + ", your age is: " + age);
}
input.close();
}catch(IOException ex){
System.err.println(ex);
}
}
}
我假设您输入的一行是这样的:
Joe C
在这种情况下,您对next()
第一次调用将返回Joe
,而第二个调用将返回C
现在,当您调用nextInt()
,这里没有任何内容可供读取。 因此, NoSuchElementException
。
您可以这样更改:
import java.util.*;
import java.io.*;
public class FileIO
{
public static void main( String args[] )
{
String sourceFile = "inputfile.txt";
String destinationFile = "outputfile.txt";
try{
File sfile = new File(sourceFile);
Scanner input = new Scanner(sfile);
while(input.hasNext())
{
String fname = input.next();
String lname = "";
if (input.hasNext())
lname = input.next();
int age = -1;
if (input.hasNext())
age = input.nextInt();
System.out.println(fname + ' ' + lname + ", your age is: " + age);
}
input.close();
}catch(IOException ex){
System.err.println(ex);
}
}
}
您的程序运行良好!
确保inputfile.txt类似于:
String
String
int
并且存在于工作目录中。 要找到工作目录,可以将其添加到代码中:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.