我在写一个程序,它从文件中读取输入,然后将其打印到屏幕上。当我运行它而没有从文件输入时,它工作得很好。但是,每次我尝试从文件运行它时,它都会给我一个“线程中的异常”主“java.util.NoSuchElementException:没有找到线”的错误,该错误发生在每个要输入的地方。我不知道发生了什么事。从文件输入运行Java程序
这个程序假设从用户处获取输入,创建一个Photo对象,然后将信息打印到屏幕上。当我手动输入信息时,一切运行良好,但是当我尝试使用java PhotoTest < test.dat获取文件的输入时,它会显示以下错误消息:
线程“main”中的异常java.util.NoSuchElementException:没有找到行
在java.util.Scanner.nextLine(Scanner.java:1516)
在PhotoTest.readPhoto(PhotoTest.java:31)
在PhotoTest.main(PhotoTest.java:74)
我的代码有输入:
private static Photo readPhoto(Scanner scanner) throws ParseException
{
Date dateTaken;
Scanner scan = new Scanner(System.in);
String subject = scan.nextLine();
subject = subject.trim();
String location = scan.nextLine();
location = location.trim();
String date = scan.nextLine();
date = date.trim();
if (date.equals("")){ //if the date is empty it is set to null
dateTaken = null;
}
else { //if a date is entered, it is then parsed
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
dateTaken = df.parse(date);
}
String file = scan.nextLine();
file = file.trim();
File photoFile = new File(file);
//creates a Photo object from the information entered
Photo Photo = new Photo(subject, location, dateTaken, photoFile);
return Photo;
}
public static void main(String[] args) throws ParseException
{
boolean endprogram = false;
Scanner scan = new Scanner(System.in);
//creates a loop so that the user may enter as many photos as they wish
while (!endprogram)
{
System.out.println("Would you like to enter a photo (y/n)?");
//if the input is anything other than y, the program ends
if(!scan.next().equalsIgnoreCase("y"))
{
endprogram = true;
}
else
{
System.out.println(readPhoto(scan));
}
}
}
这是真正的密码?如果你不在readPhoto方法上返回一张照片,它甚至不会编译,并且发布实际读取该文件的代码会有所帮助 – marcosbeirigo
@Katy:在这一点上无法帮助你。你需要更清楚你的程序应该做什么。展示代码时,还要确保它捕捉到问题的本质。你目前的代码有许多甚至与问题无关的问题。 – polygenelubricants