簡體   English   中英

使用文件輸入運行Java程序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM