Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: console skipping input

Tags:

java

console

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.

like image 441
zerodeficit Avatar asked Dec 04 '25 11:12

zerodeficit


1 Answers

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();
   }
like image 149
Yogendra Singh Avatar answered Dec 06 '25 05:12

Yogendra Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!