[英]Running a Java program with input from a file
我正在编写一个程序,该程序从文件中读取输入,然后将其打印到屏幕上。 当我在不从文件中获取输入的情况下运行它时,它运行得很好。 但是,每次我尝试从文件中运行它时,都会给我一个“线程“主”中的异常” java.util.NoSuchElementException:在找不到输入的地方都会发生的错误。 我不知道发生了什么。
假定该程序接收用户的输入,创建Photo对象,然后将信息打印到屏幕上。 当我手动输入信息时,一切运行正常,但是当我尝试使用java PhotoTest <test.dat来获取文件的输入时,它给出此错误消息:
线程“主”中的异常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));
}
}
}
当我手动输入信息时,一切正常,但是当我尝试使用
java PhotoTest < test.dat
来获取文件的输入时[...]
test.dat
是否也包含"y"
确认? 当您通过管道stdin
的文件时,该文件的内容必须为合法格式,就像手动键入一样。
另外,你在另外一台Scanner
,例如stdin
,即使一个已经被传递到readPhoto
。 您确定需要这样做吗?
在文件中,您需要在最后一行输入回车符。 那将等同于您手动键入的内容。 请注意,键入时,在最后一行中按Enter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.