Stavern
Stavern

Reputation: 13

Read an input of trillions value?

I want to know how to read a number from 1 to trillions in My Java application without an error.

This is the part of my code:

Scanner sc = new Scanner(System.in);
System.out.print("Enter your money value : ");
long value = sc.nextInt();
System.out.print("Your money in String : "+value);

If I enter a value from about 1 to 2.111.111.999 it works fine but every time I run it and enter greater than that, there's this error message :

Exception in thread "main" java.util.InputMismatchException: For input string: "1000000000000"
at java.util.Scanner.nextInt(Scanner.java:2097)
at java.util.Scanner.nextInt(Scanner.java:2050)
at konversiangka.Konversiangka.main(Konversiangka.java:28)

Java Result: 1

I guess this is a "data type" mistake. I know if you want to store a trillion in a long data type you have to add "L" in the end of the value, like this, "1000000000000L". But I don't want User to add that when they enter a value on the program,

So can you help Me how to do that? I Appreciate any suggestion and correction, thanks.

Upvotes: 1

Views: 756

Answers (2)

ug_
ug_

Reputation: 11440

You can use a long as Tharwen mentioned or you can use java.math.BigDecimal. BigDecimal is a class made for holding a decimal number as big (or small) as you want. You can see all the primitive data types and their max/min size here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Scanner sc = new Scanner(System.in);
System.out.print("Enter your money value : ");
BigDecimal value = sc.nextBigDecimal();
System.out.print("Your money in String : "+value);

Output:
Enter your money value : 271075217301782039710237102710521231.23
Your money in String : 271075217301782039710237102710521231.23

Upvotes: 2

Tharwen
Tharwen

Reputation: 3107

Use

long value = sc.nextLong();

instead.

The reason for the error is that the maximum value that can be put into an int is 2,147,483,647, and even though you declared the variable as a long, Scanner.nextInt() always tries to convert the number into an int.

Upvotes: 3

Related Questions