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

标签 java

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

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

 '**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/

相关文章:

java - Java ReSTLet API 可以与 REST PHP API 一起使用吗?

java - GWT 客户端 : java. util 还是 com.google.gwt.dev.util?

java - iPhone 应用程序中的 3DES 加密总是产生与 Java 中的 3DES 加密不同的结果

java - 安卓 : Add item to top of arraylist

java - 如果 java 堆内存限制与 kubernetes 中的 pod 资源限制不同,会发生什么情况?

java - JLabel mousePressed 相同的标签根据状态不同的操作

java - 在 Eclipse Android 项目中运行带有 main(String[] args) 的 Java 类作为 Java 应用程序导致 "Invalid layout of java.lang.String at value"

c# - Java中数组继承自什么?我可以这样做吗?

java - 多次使用 MediaPlayer - Android

java - 如何在不创建另一个类的情况下创建内部 child ?