gpt4 book ai didi

java - 使用来自文件的输入运行 Java 程序

转载 作者:行者123 更新时间:2023-12-02 00:52:28 26 4
gpt4 key购买 nike

我正在编写一个程序,它从文件中读取输入,然后将其打印到屏幕上。当我运行它而不从文件中获取输入时,它工作得很好。但是,每次我尝试从文件运行它时,都会出现“线程“main”java.util.NoSuchElementException 中的异常:找不到行”错误,该错误出现在每个应该读取输入的位置。我不知道发生了什么。

该程序假设接受用户的输入,创建一个 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));
}

}
}

最佳答案

Everything runs fine when I am entering the information manually but when I try to use java PhotoTest < test.dat to get the input for[sic?] a file [...]

test.dat包含"y"也确认?当您通过管道输入 stdin 的文件时,该文件的内容必须采用合法格式,就像手动输入的一样。

<小时/>

此外,您正在创建另一个 Scanner stdin 的实例即使其中一个已经传递给 readPhoto 。您确定需要这样做吗?

关于java - 使用来自文件的输入运行 Java 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2436645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com