java:在BigInteger的情况下如何进行循环工作 [英] java: how for loop work in the case of BigInteger

查看:166
本文介绍了java:在BigInteger的情况下如何进行循环工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将用户的输入作为Big-Integer并将其操作为For循环

I want to take Input from the user as Big-Integer and manipulate it into a For loop

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

但它不起作用

任何人都可以帮助我。

推荐答案

你改用这些语法:

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

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

So here's an example of putting it together:

    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 通常就足够了。

Note that using BigInteger as a loop index is highly atypical. long is usually enough for this purpose.


  • java.math.BigInteger

    • java.math.BigInteger
      • int compareTo(BigInteger val) from interface Comparable<T>
      • BigInteger subtract(BigInteger val)
      • BigInteger add(BigInteger val)
      • static BigInteger valueOf(long val)

      来自文档:


      这个方法优先于六个布尔比较运算符中的每一个的单独方法(< == > > = != < = )。建议执行这些比较的习惯用法是:( x.compareTo(y) < op> 0 ),其中 < op> 是六个比较运算符之一。

      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 ,这些是比较习语:

      In other words, given BigInteger x, y, these are the comparison idioms:

      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>

      This is not specific to BigInteger; this is applicable to any Comparable<T> in general.

      BigInteger ,如 String ,是一个不可变对象。初学者倾向于犯下以下错误:

      BigInteger, like String, is an immutable object. Beginners tend to make the following mistake:

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

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

      Since they're immutable, these methods don't mutate the objects they're invoked on, but instead return new objects, the results of those operations. Thus, the correct usage is something like:

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

      这篇关于java:在BigInteger的情况下如何进行循环工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆