gpt4 book ai didi

Java 应用程序在 nextLine() 上崩溃

转载 作者:行者123 更新时间:2023-12-02 06:18:34 24 4
gpt4 key购买 nike

我的应用程序在到达 main 中的 scan.getLine() 时总是崩溃。我收到的错误是“java.util.NoSuchElementException:找不到行”。

这是代码:

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = new String();
int operation=0;
operation = getOperation();
System.out.print("Enter string:");
s = scan.nextLine(); // program crashes before I have the chance to input anything
System.out.println(s);
scan.close();

}
public static int getOperation(){ //get operation between 1-10
Scanner scan= new Scanner(System.in);
boolean input=true;
int op=0;
while (input){ // get correct input from the user
if (scan.hasNextInt())
{
op=scan.nextInt();
if (op < 1 || op > 10)
System.out.print("Please enter valid operation 1-10:");
else
input=false;
}
else
System.out.print("Please enter valid operation 1-10:");
scan.nextLine(); // to clear the buffer
}
scan.close();
return op;
}

奇怪的是,当我在编写 getOperation 函数之前插入时,并且整个 getOperation 位于 main 内,应用程序运行良好。仅当我将代码移至 getOperation 方法后,scan.nextLine() 才会崩溃,甚至在我进行更改以在控制台中输入任何内容之前。

最佳答案

尝试使用这个小代码片段

public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
Scanner s2 = new Scanner(System.in);
s2.close();
s1.nextLine();
}

close函数关闭System.in的InputStream

由于您要在 getOperation() 中使用 scan.close(); 关闭扫描仪,因此对具有相同 InputStream 的另一个扫描仪进行以下调用将导致您出现以下异常:正在遇到。

关于Java 应用程序在 nextLine() 上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32825339/

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