繁体   English   中英

如何修复java.util.NoSuchElementException

[英]How can I fix java.util.NoSuchElementException

我想修复java.util.NoSuchElementException错误。 我不断收到错误:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Main.newUser(Main.java:28)
    at Main.main(Main.java:18)

用这个代码

import java.util.Scanner;
import java.io.*;
class Main2
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        input.close();
        newUser();
    }
    private static void newUser()
    {
        try
        {
            Scanner input = new Scanner(System.in);
            System.out.println("Please enter the name for the new user.");
            String userNameNew = input.nextLine();
            System.out.println("Please enter the password for the new user.");
            String userPassWordNew = input.nextLine();
            System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
            PrintWriter out = new PrintWriter("users.txt");
            out.print(userNameNew + "\r\n" + userPassWordNew);
            out.close();
            input.close();
        } catch (IOException e) { e.printStackTrace(); }
    }
}

你能帮我么? 谢谢。

我找到了您收到此异常的原因。

因此,在您的main方法中,您初始化了Scanner类对象并立即将其关闭。

这是问题所在。 因为当扫描程序调用close()方法时,如果源实现了Closeable接口,它将关闭其输入源。

关闭扫描器后,如果源实现了Closeable接口,它将关闭其输入源。

https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

输入流类(作为您的输入源)实现了Closeable接口。

https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html

进一步,您将Scanner类对象初始化为newUser()方法。 此处,扫描程序类对象已成功初始化,但您的输入源仍然关闭。

因此,我的建议是仅关闭一次扫描器类对象。 请找到您的更新代码。

    class Main2
    {
        public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        newUser(input); 
      //input.close()
    }
    private static void newUser(Scanner input) 
    {
        try {
            System.out.print("Please enter the name for the new user.");
            String userNameNew = input.nextLine();
            System.out.println("Please enter the password for the new user.");
            String userPassWordNew = input.nextLine();
            System.out.println("The new user: " + userNameNew + " has the password: " + userPassWordNew + "." );
            PrintWriter out = new PrintWriter("users.txt");
            out.print(userNameNew + "\r\n" + userPassWordNew);
            out.close();
        } catch (IOException e) { e.printStackTrace(); }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM