我对Java编程比较陌生。最近我决定创建一个随机系统,根据请求存储,写入和读取信息。在阅读我已经使用该程序编写的文件时,我收到以下错误:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ReadFile.readFile(ReadFile.java:24)
at User.main(User.java:35)
我假设这个错误是User类调用ReadFile类的结果,因为到目前为止该程序的其余部分工作正常。
属于的用户类:
import java.io.*;
import java.util.*;
public class User
{
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
Scanner user_input = new Scanner(System.in);
String input;
System.out.println("User Information System:");
System.out.println("Please type the full name of the person you wish to lookup.");
input = user_input.nextLine();
System.out.println("UIS currently has the following data on " + input + ":");
if(input.equals("First Last"))
{
System.out.println("Opening Data on " + input + "...");
}
else
{
System.out.println("No Data found.");
}
if(input.equals("/create"))
{
CreateFile create = new CreateFile();
create.openFile();
create.addRecords();
create.closeFile();
}
if(input.equals("/read"))
{
ReadFile read = new ReadFile();
read.openFile();
read.readFile();
read.closeFile();
}
}
}
与ReadFile类一样:
import java.io.*;
import java.util.*;
public class ReadFile
{
static Scanner scanner;
public void openFile()
{
try
{
scanner = new Scanner(new File("TestFile.txt"));
}
catch(Exception e)
{
System.out.println("Error reading file.");
}
}
public void readFile()
{
while(scanner.hasNext()) //Find a way to shorten this to a loop of printing whatever is in the file.
{
String a = scanner.nextLine();
String b = scanner.next();
String c = scanner.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
scanner.close();
}
}