2017-03-09 63 views
0

我試圖找出這個編譯錯誤:斯卡拉錯誤:標識符預期,但「}」發現

Error:(51, 4) identifier expected but '}' found. 
    } else if (n < 0) { 
^

對於此代碼:

def nthPowerOfX(n: Int, x:Double) : Double = { 
    if (n == 0) { 
    1.0 
    } else if (n < 0) { 
    1.0/nthPowerOfX(n,x) 
    } else if (n % 2 == 0 && n > 0) { 
    nthPowerOfX(2, nthPowerOfX(n/2,x)) 
    } else { 
    x*nthPowerOfX(n-1, x) 
    } 
} 

我試着return語句太過但沒對我的理解無關緊要。

+1

您的代碼段中可能沒有語法錯誤,可能是您的代碼的其他部分。另外考慮使用模式匹配而不是'if else' –

回答

0

約瑟夫是對的!沒有錯誤。請考慮使用此:

def nthPowerOfX(n: Int, x:Double) : Double = { 
    n match{ 
     case 0 => 1.0 
     case x if x < 0 => 1.0/nthPowerOfX(n,x) 
     case x if x % 2 == 0 && x > 0 => nthPowerOfX(2, nthPowerOfX(n/2,x)) 
     case x => x*nthPowerOfX(n-1, x) 
    } 
    } 

但是請記住,遞歸是危險的事情,最好還是使用尾遞歸,如果我們談論的是斯卡拉。