我正在尝试使用 in.nextLine()
从控制台输入中解析一个字符,然后从那里获取 charAt(0)
。我的问题是在要求用户输入一个字符串以执行 in.nextLine()
之后,它会跳过输入并由于试图获取空字符串的第一个字符而产生错误。
System.out.print("Select an operator (+, -, *, /), 'c' or 'C' to clear, or 'q' to quit: ");
String temp = in.nextLine();
char tempOperator = temp.charAt(0);
错误是
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
完整程序可用here
欢迎提出一般性意见和建议。 提前致谢。
最佳答案
当您执行 cValue = in.nextDouble();
时,它会读取下一个标记(完整值)并将其解析为加倍。如果此时按下了返回键,\n
就是缓冲区中要读取的下一个标记。
当您执行以下操作时:String temp = in.nextLine();
,它会从前一个输入的缓冲区中读取 \n
和 charAt(0 )
失败,因为它只读取了空 ("") 字符串。
为了克服这个问题,要么通过添加一个 in.nextLine()
来跳过上一个缓冲区,添加 \n\r
作为跳过模式,如下所示(这是Scanner.class
中定义的模式为 LINE_SEPARATOR_PATTERN
):
in.skip("\r\n|[\n\r\u2028\u2029\u0085]");
或者放一个小的 while
循环如下:
String temp = "";
while((temp.length() < 0){
temp = in.nextLine();
}
关于Java:控制台跳过输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13161870/