gpt4 book ai didi

java - 如何修复 java.util.NoSuchElementException

转载 作者:行者123 更新时间:2023-12-02 10:00:20 25 4
gpt4 key购买 nike

我想修复 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 类对象并立即关闭它。

问题就在这里。因为当scanner调用close()方法时,如果输入源实现了Closeable接口(interface),它就会关闭它的输入源。

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

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

InputStream 类是您案例中的输入源,它实现了 Closeable 接口(interface)。

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(); }
}
}

关于java - 如何修复 java.util.NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55680884/

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