How to store a large (10 digits) integer?
Which Java data type would be able to开发者_开发知识库 store a big numerical value, like 9999999999?
Your concrete example could be stored in long
(or java.lang.Long
if this is necessary).
If at any point you need bigger numbers, you can try
java.math.BigInteger
(if integer), or java.math.BigDecimal
(if decimal)
In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L
or l
to tell the compiler that it's a long
constant:
long l1 = 9999999999; // this won't compile
long l2 = 9999999999L; // this will work
You can store this in a long
. A long
can store a value from -9223372036854775808
to 9223372036854775807
.
A primitive long or its java.lang.Long wrapper can also store ten digits.
Use BigInt datatype with its implicit operations. The plus point for it is it will not give answers in exponential representation. It will give full length result
Here is an example of addition
BigInteger big1 = new BigInteger("1234567856656567242177779");
BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
BigInteger bigSum = big1.add(big2);
System.out.println(bigSum );
you can use long or double.
You could store by creating an object that hold a string value number to store in an array list.
by example: BigInt objt = new BigInt("999999999999999999999999999999999999999999999999999");
objt is created by the constructor of BigInt class. Inside the class look like.
BigInt{
ArrayList<Integer> myNumber = new ArrayList <Integer>();
public BigInt(){}
public BigInt(String number){ for(int i; i<number.length; i++){ myNumber.add(number.indexOf(i)); } }
}
A wrapper class java.lang.Long can store 10 digit easily.
Long phoneNumber = 1234567890;
It can store more than that also.
Documentation:
public final class Long extends Number implements Comparable<Long> {
/**
* A constant holding the minimum value a {@code long} can
* have, -2<sup>63</sup>.
*/
@Native public static final long MIN_VALUE = 0x8000000000000000L;
/**
* A constant holding the maximum value a {@code long} can
* have, 2<sup>63</sup>-1.
*/
@Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
}
This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.
If you want to take user input then you should take that as string, then convert that into long.
//Take user input using Scanner class
Scanner sc = new Scanner(System.in);
String str = sc.next();
//Convert that to long
long num = Long.parseLong(str);
System.out.println(num); // This is not a string anymore
精彩评论