new to programming here. I am having a bit of difficulty to transform a Switch statement to an If statement. Any help and explanation would be appriciated.
public void setScale(String scale){
//everything will be in lower case
switch (scale.toLowerCase()) {
//convert for Celsius - 0 since first place holder in array
case "c":
case "celsius":
if (!this.scale.equals(scales[0])) {
convertToCelsius();
this.scale = scales[0];
}
break;
default:
System.out.println("Invalid value of scale! Try again");
}
}
This is what I think should be. I just want to know if this is the right way to go about it.
public void setScale(String scale){
if(scale == "C" || scale == "celsius"){
if(this.scale != scales[0]){
convertToCelsius();
this.scale = scales[0];
}
}
else{
System.out.println("Invalid scale");
}
}
If you are new to programming, it is very important you learn first the basics of the language. There are dozens of tutorials free of cost on the Internet. In my opinion, to learn Java the Java Tutorials site is the most comprehensive information source. Anyway, here is the explanation for using if
and switch
statements:
Usage of the ==
operator: when applied on objects (instances of a class) it checks if two references are pointing to the same object.
Example
String s1 = "Hello";
String s2 = s1;
s1 == s2 => true // because both references s1 and s2 point to the same String object
But this is not true for two reference variables pointing to two different instances as in the following case:
String s1 = new String("Hello");
String s2 = new String("Hello");
s1 == s2 => false
s1.equals(s2) => true
So you have to use either the equals
method or the equalsIgnoreCase()
method. Take a look at the definition of equals
and equalsIgnoreCase
methods here .
Finally, your code should look like:
public void setScale(String scale){
if("C".equalsIgnoreCase(scale) || "celsius".equalsIgnoreCase(scale)) {
if(!this.scale.equals(scales[0])) {
convertToCelsius();
this.scale = scales[0];
}
} else {
System.out.println("Invalid scale");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.