所以,我一直有这个问题.我试图让这个方法返回给它的字符串的第一个字符,但我一直得到java.util.NoSuchElementException ...我想我可能会使用一些语法错误,但我真的不知道.有帮助吗?
public static char nthChar (){
Scanner sc = new Scanner(in);
String input = sc.nextLine();
char [] userCharArray = new char[input.length()];
userCharArray = input.toCharArray();
sc.close();
return userCharArray[0];
}
Run Code Online (Sandbox Code Playgroud)
请注意,我导入了java.lang.System的静态成员我将其更改为此...
public static char nthChar (){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
char [] userCharArray = input.toCharArray();
sc.close();
return userCharArray[0];
}
Run Code Online (Sandbox Code Playgroud)
仍然无法正常工作.
这看起来像是我的嫌疑人:
sc.close();
Run Code Online (Sandbox Code Playgroud)
当您关闭该扫描仪时,您也关闭了System.in.从System.in读取的新扫描程序的后续读取将抛出NoSuchElementException,因为基础流已关闭.
所以你需要删除它,并查看你的代码,并确保你没有在其他地方关闭System.in.虽然通常你应该在完成它们时关闭你的流,但System.in是一个特例,你不需要(也不应该)关闭从中读取的流.
例如,这将抛出NoSuchElementException:
Scanner in1 = new Scanner(System.in);
in1.close();
Scanner in2 = new Scanner(System.in);
String line = in2.nextLine(); // throws the exception
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |