簡體   English   中英

將語句切換為 If 語句 - JAVA

[英]Switch statement to If statements - JAVA

在這里編程的新手。 我在將 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");
}

  }

如果您不熟悉編程,那么首先學習該語言的基礎知識非常重要。 互聯網上有幾十個免費的教程。 在我看來,要學習 Java, Java 教程站點是最全面的信息來源。 無論如何,這里是使用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方法的定義。

最后,您的代碼應如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM