簡體   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