我有一个for
循环BigInteger
s,如下所示:
for(BigInteger a = BigInteger.valueOf(1); a.compareTo(someBigInteger); ++a) {...
显然,我不能在非原语上使用++
运算符。我该如何解决这个问题?
此外,我必须在此方案中使用BigInteger
。
答案 0 :(得分:7)
++a
是前缀增量,而不是后缀增量,但在for循环的上下文中它并不重要,因为无论如何忽略该语句的返回值。无论如何,可以通过调用BigInteger.add
来实现此功能。另请注意,compareTo
返回int
,并且由于Java在int
和boolean
之间没有隐式强制转换(例如,C表示),因此您需要必须将其结果与0进行比较,以查看a
是否小于,大于或等于someBigInteger
):
for (BigInteger a = BigInteger.ONE;
a.compareTo(someBigInteger) < 0;
a = a.add(BigInteger.ONE)) {...
答案 1 :(得分:1)
您无法重新定义operator ++以使用BigInteger,因此解决方案很简单: 1)首先声明一个BigInteger并初始化它 2)在循环中,重新分配BigInteger(在调用add方法时创建一个新的BigInteger);
private static final BigInteger LIMIT = new BigInteger("10");
public static void main(String[] args) {
new BigInteger("0");
for (BigInteger a = BigInteger.ZERO; a.compareTo(LIMIT) < 0; a = a.add(new BigInteger("1")))
System.out.println(a);
}
请参阅文档http://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html#add(java.math.BigInteger)
答案 2 :(得分:0)
你可以这样做。
for(BigInteger an = BigInteger.ONE; a.compareTo(some BigInteger); a = a.ad(BigInteger.ONE)){。