2010-03-13 55 views
0

我在寫一個程序,它從文件中讀取輸入,然後將其打印到屏幕上。當我運行它而沒有從文件輸入時,它工作得很好。但是,每次我嘗試從文件運行它時,它都會給我一個「線程中的異常」主「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)); 
     } 

    } 
} 
+1

這是真正的密碼?如果你不在readPhoto方法上返回一張照片,它甚至不會編譯,並且發佈實際讀取該文件的代碼會有所幫助 – marcosbeirigo

+1

@Katy:在這一點上無法幫助你。你需要更清楚你的程序應該做什麼。展示代碼時,還要確保它捕捉到問題的本質。你目前的代碼有許多甚至與問題無關的問題。 – polygenelubricants

回答

3

運行的一切,當我手動輸入信息很好,但是當我嘗試使用java PhotoTest < test.dat以獲取輸入[原文?]文件[...]

是否test.dat包含"y"確認嗎?當您在文件中輸入stdin時,該文件的內容必須採用合法的格式,就好像它是手動輸入的一樣。


此外,您是stdin創建另一個Scanner例如,即使一個已經被傳遞到readPhoto。你確定你需要這樣做嗎?

0

在你的文件中,你需要在最後一行回車。這將等同於您手動輸入的內容。請注意,當您輸入內容時,在最後一行中按回車。