将语句切换为If语句 - JAVA

时间:2017-10-23 16:41:36

标签: java if-statement switch-statement

这里的编程新手。我将Switch语句转换为If语句有点困难。任何帮助和解释都会得到满足。

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");


     }
  }    

这是我认为应该的。我只是想知道这是否是正确的方法。

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

  }

1 个答案:

答案 0 :(得分:0)

如果您不熟悉编程,首先要了解该语言的基础知识非常重要。互联网上有许多免费的教程。在我看来,要学习Java,Java Tutorials站点是最全面的信息源。无论如何,这是使用ifswitch语句的解释:

==运算符的用法:当应用于对象(类的实例)时,它检查两个引用是否指向同一对象。

示例

String s1 = "Hello";
String s2 = s1;

s1 == s2 => true // because both references s1 and s2 point to the same String object

但对于指向两个不同实例的两个引用变量,情况并非如此,如下例所示:

String s1 = new String("Hello");
String s2 = new String("Hello");

s1 == s2 => false
s1.equals(s2) => true 

因此,您必须使用equals方法或equalsIgnoreCase()方法。请查看equalsequalsIgnoreCase方法here的定义。

最后,您的代码应如下所示:

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