Aayush Mahajan
Aayush Mahajan

Reputation: 4033

6 billion cannot be recognized as an integer in java?

I am having problems when I try to store 6000000000 in an int variable.

This is the part of script I am having problems with:

Scanner x = new Scanner(System.in);
System.out.println("Please enter a number here:");
int k = x.nextInt();
System.out.println(k);

When I input 6000000000 the output should be the same, but the output is this error:

Exception in thread "main" java.util.InputMismatchException: For input string: "6000000000"
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)

What is this? How to prevent this?

Upvotes: 1

Views: 1697

Answers (4)

brimborium
brimborium

Reputation: 9512

Here you can see that the maximum value for int is 2,147,483,647 = 2^31 - 1. Try long instead:

long k = x.nextLong();
System.out.println(k);

long will take you up to 9,223,372,036,854,775,807 = 2^63 - 1. Once you need values over that, you can either look into BigInteger (Scanner#nextBigInteger()) or just use a floating point number like double (Scanner#nextDouble()).

Upvotes: 0

RNJ
RNJ

Reputation: 15552

or if you are using really big numbers (bigger than long) then use nextBigInteger

Upvotes: 0

pb2q
pb2q

Reputation: 59617

Use a long and nextLong, your number is larger than Integer.MAX_INT: 2^31 - 1.

Also note that you can anticipate this error if you first test the stream using hasNextInt().

Upvotes: 1

Keppil
Keppil

Reputation: 46219

The value is too big, java ints can only hold values from –2,147,483,648 to 2,147,483,647.

Use a long instead.

Upvotes: 8

Related Questions