gpt4 book ai didi

java - 使用用户输入和 FileInputStream 创建文件并从该文件读取整数时遇到问题

转载 作者:搜寻专家 更新时间:2023-11-01 03:32:11 24 4
gpt4 key购买 nike

我不能很好地解释我的问题,这是提示。

我相信我正朝着正确的方向前进,我的教授真的经历了这么快。尽管我正在使用这本书并寻求帮助,但无济于事。

 '**Ask the user to enter a filename on the keyboard, including “.txt.”  Read five integers from that file (all on the same line, separated by spaces) and tell the user their sum by printing it to the screen (console).**' 

它编译并运行,但是当输入文件名 (io.txt) 时,我得到线程“主”java.util.NoSuchElementException 中的异常:找不到行

    public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String myString = " ";
Scanner inputStream = null;


System.out.println("Please enter a Filename, including '.txt' at the end: ");
myString = in.next();

try
{

inputStream = new Scanner(new FileInputStream(myString));
}
catch(FileNotFoundException e) //Giving the file not found a name,
{
System.out.println("Invalid File or filename");
System.out.println("Or could not be found,try again");
System.exit(0);
}
//True will always add on, not overwrite

int n1 = inputStream.nextInt();
int n2 = inputStream.nextInt();
int n3 = inputStream.nextInt();
int n4 = inputStream.nextInt();
int n5 = inputStream.nextInt();

String line = inputStream.nextLine(); //wait for new line, get the next line
inputStream.close( );
System.out.println("The five numbers read from the file are: ");
System.out.println(n1+" , "+ n2 + ", "+ n3 + ", "+ n4 +", "+ n5);
System.out.println("Which adds together to eqaul: " + (n1+n2+n3+n4+n5));


}

我想要方向,而不是让别人帮我解决。

最佳答案

在测试你提供的代码后返回

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.example.Test.main(Test.java:37)

这是您代码中的以下行

String line = inputStream.nextLine(); //wait for new line, get the next line

因此您的代码尝试从文件中读取另一行,但找不到。实际上,这意味着您的代码期望读取"1 2 3 4 5\n" 来自文件 io.txt 而该文件实际上包含 "1 2 3 4 5"(没有文件末尾的换行符)。

但是,由于您已经阅读了所需的所有整数,因此您可以就此打住。

还要确保关闭文件流。

关于java - 使用用户输入和 FileInputStream 创建文件并从该文件读取整数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47601800/

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