Java:控制台跳过输入 [英] Java: console skipping input

查看:643
本文介绍了Java:控制台跳过输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从控制台输入使用in.nextLine()解析一个字符,并从那里带charAt(0)。我的问题是在要求用户输入一个字符串来执行in.nextLine()之后,它会跳过输入并产生一个错误,因为试图获取空字符串的第一个字符。

  System.out.print(选择要清除的运算符(+, - ,*,/),'c'或'C'退出: ); 
String temp = in.nextLine();
char tempOperator = temp.charAt(0);

错误为

  java.lang.StringIndexOutOfBoundsException:String index超出范围:0 
at java.lang.String.charAt(未知来源)

完整计划可用这里 p>

一般的意见和建议总是欢迎。
提前感谢。 cValue = in.nextDouble();

,它读取下一个令牌(完整值)并将其解析为双精度。如果此时按下返回键, \\\
是要读取的缓冲区中的下一个令牌。



当你做: String temp = in.nextLine(); ,它从缓冲区读取 \\\
并且 charAt(0)失败,因为它只读取了空()字符串。



要克服这个问题,可以通过添加 in.nextLine()跳过上一个缓冲区, code> \\\
\r 作为下面的跳过模式(这是 Scanner.class 中定义的模式 LINE_SEPARATOR_PATTERN ):

  in.skip(\r\\\
| [ \\\
\r\\\
\\\
\\\…]);

或放置一个小

  String temp =; 
while((temp.length()< 0){
temp = in.nextLine();
}


I'm trying to parse a char from console input using in.nextLine() and from there take charAt(0). My problem is after asking the user to enter a string to perform the in.nextLine() on, it skips the input and yields an error due to trying to get the first character of a null string.

System.out.print("Select an operator (+, -, *, /), 'c' or 'C' to clear, or 'q' to quit: ");
String temp = in.nextLine();
char tempOperator = temp.charAt(0);

the error is

java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)

full program is available here

General comments and suggestions always welcome. Thanks in advance.

解决方案

When you do cValue = in.nextDouble();, it reads the next token(full value) and parses it to double. If the return key was pressed at this time, \n is the next token in the buffer to read.

When you do: String temp = in.nextLine();, it reads the \n from the buffer of the previous enter and charAt(0) fails as it has read only empty("") string.

To overcome the issue, either skip the previous buffer by adding an addition in.nextLine(), add \n \r as skip pattern as below (this is the pattern defined in Scanner.class as LINE_SEPARATOR_PATTERN):

 in.skip("\r\n|[\n\r\u2028\u2029\u0085]");

or put a small while loop as below:

   String temp = "";
   while((temp.length() < 0){
      temp = in.nextLine();
   }

这篇关于Java:控制台跳过输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆