ファイルから入力を読み取り、それを画面に出力するプログラムを作成しています。ファイルから入力を取得せずに実行すると、完全に正常に機能します。ただし、ファイルから実行しようとするたびに、入力が読み取られると想定されるすべての場所で発生する「スレッド「メイン」java.util.NoSuchElementException:行が見つかりません」エラーが発生します。何が起こっているのかわかりません。
このプログラムは、ユーザーからの入力を受け取り、Photoオブジェクトを作成してから、その情報を画面に出力することを想定しています。情報を手動で入力するとすべて正常に実行されますが、java PhotoTest <test.datを使用してファイルの入力を取得しようとすると、次のエラーメッセージが表示
されます。
スレッド「main」の例外java.util.NoSuchElementException:行が見つかりません
java.util.Scanner.nextLine(Scanner.java:1516)
at PhotoTest.readPhoto(PhotoTest.java:31)
at 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));
}
}
}