1
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        System.out.println(a);

    }

}

I get the following message and don't know why.

Exception in thread "main" java.util.InputMismatchException: For input string: "999999999999999"
    at java.util.Scanner.nextInt(Scanner.java:2123)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at codingexercises.Main.main(Main.java:9)

I want to know how to fix the problem.

1
  • Cause the number you have entered is too large, use long instead of int. Commented Apr 26, 2020 at 6:27

3 Answers 3

4

999,999,999,999,999 is too large to fit in an int.

Use nextLong() or nextBigInteger() if you need to support numbers larger than 2,147,483,647.

long can handle values up to 9,223,372,036,854,775,807.

BigInteger doesn't have a specified limit.

Sign up to request clarification or add additional context in comments.

Comments

2

Replace

int a = sc.nextInt();

with

long a = sc.nextLong()

In Java, the Java Language Specification determines the representation of the data types.

The order is: byte 8 bits, short 16 bits, int 32 bits, long 64 bits. All of these types are signed, there are no unsigned versions. However, bit manipulations treat the numbers as they were unsigned (that is, handling all bits correctly).

The character data type char is 16 bits wide, unsigned, and holds characters using UTF-16 encoding (however, it is possible to assign a char an arbitrary unsigned 16 bit integer that represents an invalid character codepoint)

          width                     minimum                         maximum

SIGNED
byte:     8 bit                        -128                            +127
short:   16 bit                     -32 768                         +32 767
int:     32 bit              -2 147 483 648                  +2 147 483 647
long:    64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807

UNSIGNED
char     16 bit                           0                         +65 535

Comments

1

Try with the following code. It will help to solve your problem:

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        BigInteger a = sc.nextBigInteger();
        System.out.println(a);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.