java:在BigInteger的情况下for循环如何工作

新手上路,请多包涵

我想将用户的输入作为 Big-Integer 并将其操纵到 For 循环中

BigInteger i;
for(BigInteger i=0; i<=100000; i++) {
    System.out.println(i);
}

但它不会工作

有谁能够帮我。

原文由 Sanjeev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 538
2 个回答

您改用这些语法:

 BigInteger i = BigInteger.valueOf(100000L);  // long i = 100000L;
i.compareTo(BigInteger.ONE) > 0              // i > 1
i = i.subtract(BigInteger.ONE)               // i = i - 1

所以这里有一个把它放在一起的例子:

     for (BigInteger bi = BigInteger.valueOf(5);
            bi.compareTo(BigInteger.ZERO) > 0;
            bi = bi.subtract(BigInteger.ONE)) {

        System.out.println(bi);
    }
    // prints "5", "4", "3", "2", "1"

请注意,使用 BigInteger 作为循环索引是非常不典型的。 long 通常就足够了。

API链接


compareTo 成语

从文档中:

This method is provided in preference to individual methods for each of the six boolean comparison operators ( < , == , > , >= , !=<= )。 The suggested idiom for performing these comparisons is: ( x.compareTo(y) <op> 0 ), where <op> is one of the six comparison operators.

换句话说,给定 BigInteger x, y ,这些是比较习语:

 x.compareTo(y) <  0     // x <  y
x.compareTo(y) <= 0     // x <= y
x.compareTo(y) != 0     // x != y
x.compareTo(y) == 0     // x == y
x.compareTo(y) >  0     // x >  y
x.compareTo(y) >= 0     // x >= y

这不是特定于 BigInteger ;这通常适用于任何 Comparable<T>


关于不变性的注意事项

BigIntegerString 一样,是一个不可变对象。初学者容易犯以下错误:

 String s = "  hello  ";
s.trim(); // doesn't "work"!!!

BigInteger bi = BigInteger.valueOf(5);
bi.add(BigInteger.ONE); // doesn't "work"!!!

由于它们是不可变的,因此这些方法不会改变调用它们的对象,而是返回新对象,即这些操作的结果。因此,正确的用法是这样的:

 s = s.trim();
bi = bi.add(BigInteger.ONE);

原文由 polygenelubricants 发布,翻译遵循 CC BY-SA 2.5 许可协议

嗯,首先,你有两个名为“i”的变量。

其次,用户输入在哪里?

第三,i=i+i 将 i 拆箱为一个原始值,可能会溢出它,然后将结果装箱到一个新对象中(也就是说,如果该语句甚至可以编译,我还没有检查过)。

第四,i=i+i可以写成i = i.multiply(BigInteger.valueof(2))。

第五,循环永远不会运行,因为 100000 <= 1 是错误的。

原文由 Justin K 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题