• Post Reply Bookmark Topic Watch Topic
  • New Topic

BigInteger usage  RSS feed

 
Jessica Stensrud
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi and thanks in advance.
I'm trying to use the BigInteger class after importing it: import java.math.BigInteger;

I am trying to define it using an input number so that I can check if an input number too large and give an out of bounds message.
But if I say:
BigInteger bigInteger1 = new BigInteger ("InputNumber");
if ( bigInteger1 > 999999999999 )
{
System.out.println( "Out of bounds! Too High - Try again!" ) ;
}
I get: input number is too large

even if I define a bigInteger2 = 999999999

I get the same thing.

 
Tim Harris
Ranch Hand
Posts: 57
3
Chrome Eclipse IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Couple things:

Firstly, 999999999999 also needs to be declared as a big integer.
Secondly, you can't directly compare two BigIntegers - use compareTo instead. Example:
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tim, that should be: test.compareTo(new BigInteger("999999999999")) > 0
 
Tim Harris
Ranch Hand
Posts: 57
3
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, you're right. You could also replace "> 0" with "== 1", since compareTo only returns -1, 0, or 1.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is true for BigInteger, but it's good to get in the habit of comparing against 0 instead, because other classes may return values other than -1 and 1.
 
Jessica Stensrud
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much - I'll try that!
 
Jessica Stensrud
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Close but no cigar.

When I do this:
BigInteger test = new BigInteger ("1000000000000");
if ( test.compareTo( new BigInteger("999999999999") == 0))
{
System.out.println( "Out of bounds! Too High - Try again!" ) ;
}

I get: incomparable types: java.math.BigInteger and int same thing if I use ">" instead of "=="

 
Tim Harris
Ranch Hand
Posts: 57
3
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your syntax is slightly off:

You only want the BigInteger in the compareTo function (check out the Javadoc for how it works) and you had "== 0" in there as well.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!