与输入从文件中运行Java程序
-
19-09-2019 - |
题
我写一个程序,读取来自文件的输入,然后将其打印到屏幕。当我没有从文件中取输入运行它,它完美的罚款。然而,每次我试图从文件中运行它,它给了我一个主“在线程异常‘’java.util.NoSuchElementException:没有发现在行”错误每出现一个输入被假设是阅读的地方。我不知道是怎么回事。
此程序被假设取来自用户的输入,创建一个照片对象,然后打印信息到屏幕上。一切运行,当我手动输入信息很好,但是当我尝试用java PhotoTest 我的代码,其具有输入: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));
}
}
}
解决方案
运行的一切,当我手动输入信息很好,但是当我尝试使用
输入java PhotoTest < test.dat
以获取[原文?]文件[...]
是否test.dat
包含"y"
确认吗?当你在stdin
一个文件管道,该文件的内容必须以法律形式,如果它是键入手动。
此外,您正在创建Scanner
即使一个已经被传递到另一个stdin
例如readPhoto
。你确定你需要做到这一点?
其他提示
在您的文件,你需要在最后一行回车。这将是相当于你手动输入的内容。请注意,当你输入,在最后一行按ENTER键。