2012-10-18 40 views
1

如果我使用compareToBigInteger,我該如何從結果中選擇要調用的函數? (-1 = funcA,+1 = funcB,0 =沒有函數)。基於compareTo的調用方法?

特別是:這是怎麼回事?

doCompare() { 
    BigInteger x = new BigInteger(5); 
    BigInteger y = new BigInteger(10); 

    //syntax error token "<", invalid assignment operator 
    x.compareTo(y) < 0 ? funcA() : funcB(); 
} 

void funcA(); 
void funcB(); 
+0

爲什麼不將結果轉換爲臨時值並且如果/ else? – kosa

+0

因爲這只是一個抽象我的問題的例子... – membersound

回答

0

首先,您使用BigInteger()構造不當,它需要String不是intlong。而你的函數必須有boolean返回類型,否則你不能在三元操作中使用它們。

void doCompare() 
    { 
     BigInteger x = new BigInteger("5"); 
     BigInteger y = new BigInteger("10"); 

     boolean result = x.compareTo(y) < 0 ? funcA() : funcB(); 
    } 

    boolean funcA(){return true;}; 
    boolean funcB(){return false;}; 
6

由於funcA()funcB()有返回類型void,您不能使用the ternary syntax。你可以把它改寫爲一個普通if聲明雖然不是:

if (x.compareTo(y) < 0) { 
    funcA(); 
} else { 
    funcB(); 
} 
0

使用此,

公共無效doCompare(){ BigInteger的 X =新的BigInteger( 「5」); BigInteger y = new BigInteger(「10」);

//syntax error token "<", invalid assignment operator 
    if(x.compareTo(y) < 0) 
    { 
     funcA(); 
    } 
    else 
    { 
     funcB(); 
    } 
} 

public void funcA() 
{ 
} 

public void funcB() 
{ 
} 

,如果你想使用條件在同一行,你需要修改functiones:

public void doCompare() 
{ 
    BigInteger x = new BigInteger("5"); 
    BigInteger y = new BigInteger("10"); 

    boolean a = (x.compareTo(y) < 0) ? funcA() : funcB(); 

} 

public boolean funcA() 
{ 
    return false; 
} 

public boolean funcB() 
{ 
    return true; 
}