java 等待控制台输入,Java:控制台跳过输入

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值