2012-10-18 37 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; 
}