문제

파일에서 입력을 읽는 프로그램을 작성한 다음 화면에 인쇄합니다. 파일에서 입력을 취하지 않고 실행하면 완벽하게 잘 작동합니다. 그러나 파일에서 실행하려고 할 때마다 "스레드의 예외"Main "Java.util.nosuchelementException : 입력이 읽는 모든 장소에서 발생하는 오류"에서 찾은 선이 없습니다. 나는 무슨 일이 일어나고 있는지 전혀 모른다.

이 프로그램은 사용자로부터 입력을 취하고 사진 객체를 작성한 다음 화면에 정보를 인쇄한다고 가정합니다. 정보를 수동으로 입력 할 때 모든 것이 잘 실행되지만 Java Phototest <test.dat를 사용하여 파일의 입력을 얻으려고 할 때이 오류 메시지가 표시됩니다.
스레드의 예외 "main"java.util.nosuchelementexception : No Line Found
at 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));
        }

    }
}
도움이 되었습니까?

해결책

정보를 수동으로 입력 할 때 모든 것이 잘 작동하지만 사용하려고 할 때 java PhotoTest < test.dat sic?] 파일의 입력을 얻으려면 [...

하다 test.dat 포함 "y" 확인도? 파일에 파이프 할 때 stdin, 해당 파일의 내용은 수동으로 입력 한 것처럼 법적 형식이어야합니다.


또한, 당신은 다른 것을 창조하고 있습니다 Scanner 인스턴스 stdin 비록 하나가 이미 통과 되었음에도 불구하고 readPhoto. 이 작업을 수행해야합니까?

다른 팁

파일에는 마지막 줄에 캐리지 리턴이 필요합니다. 그것은 당신이 수동으로 입력하는 것과 동일합니다. 입력 할 때 마지막 줄에서 Enter를 누릅니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top