User Input not working with keyboard.nextLine() and String (Java)
User Input not working with keyboard.nextLine() and String (Java)
For you code Change nextLine();
to next();
and it will work.
System.out.println(Was that in Celsius or Fahrenheit?);
System.out.print((Enter C for Celsius and F for Fahrenheit) );
type = keyboard.next();
to get an idea for you to what happened was this:
- nextLine(): Advances this scanner past the current line and returns the input that was skipped.
- next(): Finds and returns the next complete token from this scanner.
Also like the many of the answers says use equals()
instead of using ==
The ==
checks only the references to the object are equal. .equal()
compares string.
Read more Here
Never use Scanner#nextLine
after Scanner#nextInt
. Whenever you hit enter button after Scanner#nextInt
than it will skip the Scanner#nextLine
command. So,
Change from
int temp = keyboard.nextInt();
to
int temp = Integer.parseInt(keyboard.nextLine());
User Input not working with keyboard.nextLine() and String (Java)
.nextInt()
does not read the end of line character n
.
You need to put a keyboard.nextLine()
after the .nextInt()
and then it will work.