斯卡拉错误:标识符预期,但“}”发现

问题描述:

我试图找出这个编译错误:斯卡拉错误:标识符预期,但“}”发现

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' –

约瑟夫是对的!没有错误。请考虑使用此:

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

但是请记住,递归是危险的事情,最好还是使用尾递归,如果我们谈论的是斯卡拉。