如果我使用compareTo
和BigInteger
,我如何从结果中选择要调用哪个函数? (-1 = funcA,+ 1 = funcB,0 =无函数)。
特别是:这有什么问题?
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 :(得分:6)
由于funcA()
和funcB()
的返回类型为void
,因此您无法使用the ternary syntax。您可以将其重写为常规if
语句,但是:
if (x.compareTo(y) < 0) {
funcA();
} else {
funcB();
}
答案 1 :(得分:0)
使用此,
public void doCompare() { BigInteger x = new 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() { }
如果要在一行中使用条件,则需要修改函数:
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; }
答案 2 :(得分:0)
首先,您错误地使用了BigInteger()
构造函数,而String
不是int
或long
。并且您的函数必须具有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;};