2017-06-20 25 views
0

我想比較兩個字符串在斯卡拉。以下是功能。在斯卡拉比較字符串 - 等於==

def max(x:Int, y:String): String = { 
    | if (y=="Happy") "This is comparing strings as well" 
    | else "This is not so fair" 
    | if (x > 1) "This is greater than 1" 
    | else "This is not greater than 1" 
    | } 

some answers我認爲我可以用「==」符號來比較字符串。我給出了以下輸入並獲得了以下輸出。我錯過了什麼或斯卡拉表現不同?

max (1,"Happy") 
res7: String = This is not greater than 1 

println(max(2, "sam")) 
This is greater than 1 
+4

我覺得這個問題是不是與''==但事實上,你有兩個if/else.https://stackoverflow.com/a/12560532/3072566 – litelite

+0

謝謝@litelite。我會保留這個問題供其他人蔘考。 – Dinesh

+0

@Dinesh,請接受答案。 –

回答

2

發生這種情況是因爲在scala中最後可達的語句的值是函數結果。在這種情況下,對於「max(1,」Happy「)」代碼進入y =「happy」內部,但是在進入if(x> 1)的else分支之後。因爲這是該函數中的最後一個聲明,所以你會得到它的結果。

交叉檢查它的第一個引進了打印語句,如果塊

def max(x:Int, y:String): String = { 
    | if (y=="Happy") println("This is comparing strings as well") 
    | else "This is not so fair" 
    | if (x > 1) "This is greater than 1" 
    | else "This is not greater than 1" 
    | } 

現在所說的「MAX(1,」幸福「)」

結果: 這是比較字符串,以及 這不大於1

這表明您正在比較正確的字符串。

1

您的max函數僅返回一個字符串,並且該字符串始終是最後的ifelse語句。如果你想同時得到比較輸出,那麼你應該返回一個字符串的tuple2作爲

scala>  def max(x:Int, y:String): (String, String) = { 
    |  var string1 = "This is not greater than 1" 
    |  var string2 = "This is not so fair" 
    |  if (x > 1) string1 = "This is greater than 1" 
    |  if (y=="Happy") string2 = "This is comparing strings as well" 
    |  (string1, string2) 
    |  } 
max: (x: Int, y: String)(String, String) 

scala> max(1, "Happy") 
res0: (String, String) = (This is not greater than 1,This is comparing strings as well) 

scala> res0._1 
res1: String = This is not greater than 1 

scala> res0._2 
res2: String = This is comparing strings as well 

scala> max(2, "sam") 
res3: (String, String) = (This is greater than 1,This is not so fair) 

我希望這個答案可以幫助