This question already has an answer here:
- How do I compare strings in Java? 23 answers
My code is:
import java.util.Scanner;
public class EvaluateTemperature {
public static void main(String[] args)
{
Scanner temperatureScanner = new Scanner(System.in);
Scanner unitScanner = new Scanner(System.in);
Double converted = 0.0;
System.out.println("What's the temperature now?");
int temperature = temperatureScanner.nextInt();
System.out.println("Is it Celsius or Fahrenheit?");
String unit = unitScanner.next();
System.out.println(unit == "C");
if (unit == "C")
{
converted = temperature * 1.8 + 32;
}
if (unit == "F")
{
converted = (temperature - 32) / 1.8;
}
System.out.println(converted);
temperatureScanner.close();
unitScanner.close();
}
}
The input and output in the console is:
What's the temperature now?
40
Is it Celsius or Fahrenheit?
C
false
0.0
It seems that the block code of if has not been executed because the value unit is not equal to “C” or “F”.
With the code System.out.println(unit == "C”); of which the output is “false”, it can be proved that even thought I input “C” to the value unit, the value unit is not equal to “C”.
WHY?
Thanks.
Aucun commentaire:
Enregistrer un commentaire