无法使用User Input和FileInputStream创建文件并从该文件中读取整数

时间:2017-12-01 21:34:26

标签: 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)时,我得到线程中的异常“main”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));


}

我想要指导,而不是有人为我解决它。

2 个答案:

答案 0 :(得分:1)

在测试代码后,你给它返回

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"的{​​{1}},而文件实际上包含io.txt(文件末尾没有换行符)。

但是,既然您已经阅读了所需的所有整数,那么您可以直接停在那里。

还要确保关闭文件流。

答案 1 :(得分:0)

使用.sextLine()代替.next()。