I recently started learning java during my spare time. So to practice, I\'m making a program that takes a temperature (Celsius or Fahrenheit) and converts it to the opposite
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());
You could use keyboard.next()
instead of nextLine()
and as
user1770155
mentioned to compare two strings you should use .equals()
and what I would do since you're comparing to an upper letter "C" is
type = keyboard.next().toUpperCase();
if (type.equals("C"))
Use Scanner Class:
int temp;
java.util.Scanner s = new java.util.Scanner(System.in);
String opposite, type;
double product;
System.out.print("Please enter a temperature: ");
temp = s.nextInt();
System.out.println("Was that in Celsius or Fahrenheit?");
System.out.print("(Enter 'C' for Celsius and 'F' for Fahrenheit) ");
type = s.nextLine();
if (type.equals("C")){
do something
}
else{
do something
}
For More Input references:
Scanner
BufferedReader
String
Here is a wonderful comparison on how to compare strings in 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.
Also, use type.equals("C")
instead of if (type == "C")
, the later one is comparing the reference of the value.
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