Java: console skipping input

console, java

Solution

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

Problem

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.

Original source