Number Format Exception Errors - java

I get this error whenever I run my program:
Exception in thread "main" java.lang.NumberFormatException: For input string: "9999997560"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:461)
at java.lang.Integer.valueOf(Integer.java:554)
at jsobcpuburnerpd3.Main.main(Main.java:22)
Java Result: 1
The program has two do-while loops that are nearly identical, and the first works perfectly. I only have problems with the second one.
BigDecimal lower = new BigDecimal("1000001520");
BigDecimal upper = new BigDecimal("9999997560");
int var = 2520;
String strL = lower.toString();
Integer intL = Integer.valueOf(strL);
String strU = upper.toString();
Integer intU = Integer.valueOf(strU);
Both numbers have the same amount of digits, and are converted to Integer the same way. Both are handled nearly the same way in the loops.
intL = intL + var;
intU = intU - var;
I have also attempted this without converting from BigDecimal to String, and inputting the number directly to String, but still got the same error.
EDIT I am using BigDecimal because it's a part of what my teacher wanted us to use in our work. I know it's not needed.

Obviously you will get a number format exception because the maximum value that can be store in an Integer is 2,147,483,647 which is less than 9,999,997,560.
On the other hand 1,000,001,520 is less than 2,147,483,647 which is why that works fine.
(Edit Based on Tunaki's suggestion) FYI - Moreover you really don't have to use a BigDecimal because it seems that the only reason you need it is to convert it to an Integer. So it is not required.
Also an Integer is not required because you don't seem to be requiring a reference type and hence the primitive type int should be apt. Moreover in your for loop you are adding and subtracting values from Integer which will lead to unnecessary boxing and unboxing and will be very inefficient. So use the primitive type int which would be better.

Convert the BigInteger to Integer using intValue() Method
BigDecimal lower = new BigDecimal("1000001520");
BigDecimal upper = new BigDecimal("9999997560");
Integer intBL = lower.intValue();
Integer intBU = upper.intValue();

Related

String formatting potential string doubles or integer into integers

I receive a string from a server that sometimes is a double and sometimes is an integer. And i need it to be an integer.
When i do a Integer.parseInt(confusedStringNumber)
If its a double, it throws a Number format exception. Is there a way to format the string to drop all decimal places whether they exist or not ? Thanks
int i = (int)Float.parseFloat("1.0");
int j = Float.valueOf("1.0").intValue();
Refer to the following types and methods which can give you what you're asking for:
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#round-java.math.MathContext-

Trying to find length of INT, converted to String but errors after anything > 10

I'm having trouble trying to find the length of a int inputted. I converted the int value into a string and it works perfectly up until the user inputs any int that has more than 10 digits. The program will print out how many digits were inputted but it gives some boundary error once I put anything >10 digits
answer = in.nextInt();
answerString = String.valueOf(answer);
answerLength = answerString.length();
System.out.println(answerLength);
The reason for this is because the max value for an Integer is 2147483647. If you need more digits than that consider using long.
take input as String even if it is integer value, see below code.
String answer = in.nextLine();
System.out.println(answer.length());
Using more than 10 digits goes over Integer.MAX_VALUE. BigInteger would be more suitable in your case, but be aware of its memory restrictions as mentioned here.
Just use Long answer = in.nextLong(); instead

How do i store numbers bigger than 10 billion

I am making a program and i need a way to make variables go over 10 billion and int only stores up to 999 million for me so i decided to use a long instead of a int and it turn out it only stores up to 999 million as well.
int TotalWorldPop = 7200000000;
gives me the "literal is out of range" error
long TotalWorldPop = 7200000000;
gives me the "literal is out of range" error as well
but
int TotalWorldPop = 999999999
is ok for me
A long can accommodate numbers as large as 263-1. But there's a trick to putting them into the primitive field.
If you're entering the primitive literal, then you have to add an L at the end, as all numeric literals are treated as int (and it can only go up to ~2.1 billion).
If you need numbers larger than that, use BigInteger.
You could use a BigInteger to store very large numbers.
Example:
Biginteger bigInt1 = new Biginteger("91826581752671985235272769716");
Biginteger bigInt2 = new Biginteger("-1796357891266373473772242");
Biginteger bigint3 = bigInt1.divide(bigInt2);
Biginteger bigint4 = bigInt1.add(bigInt2);

Java parsing long from string

I'm currently trying to parse some long values stored as Strings in java, the problem I have is this:
String test = "fffff8000261e000"
long number = Long.parseLong(test, 16);
This throws a NumberFormatException:
java.lang.NumberFormatException: For input string: "fffff8000261e000"
However, if I knock the first 'f' off the string, it parses it fine.
I'm guessing this is because the number is large and what I'd normally do is put an 'L' on the end of the long to fix that problem. I can't however work out the best way of doing that when parsing a long from a string.
Can anyone offer any advice?
Thanks
There's two different ways of answering your question, depending on exactly what sort of behavior you're really looking for.
Answer #1: As other people have pointed out, your string (interpreted as a positive hexadecimal integer) is too big for the Java long type. So if you really need (positive) integers that big, then you'll need to use a different type, perhaps java.math.BigInteger, which also has a constructor taking a String and a radix.
Answer #2: I wonder, though, if your string represents the "raw" bytes of the long. In your example it would represent a negative number. If that's the case, then Java's built-in long parser doesn't handle values where the high bit is set (i.e. where the first digit of a 16 digit string is greater than 7).
If you're in case #2, then here is one (pretty inefficient) way of handling it:
String test = "fffff8000261e000";
long number = new java.math.BigInteger(test, 16).longValue();
which produces the value -8796053053440. (If your string is more than 16 hex digits long, it would silently drop any higher bits.)
If efficiency is a concern, you could write your own bit-twiddling routine that takes the hex digits off the end of the string two at a time, perhaps building a byte array, then converting to long. Some similar code is here:
How to convert a Java Long to byte[] for Cassandra?
The primitive long variable can hold values in the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 inclusive.
The calculation shows that fffff8000261e000 hexademical is 18,446,735,277,656,498,176 decimal, which is obviously out of bounds. Instead, fffff8000261e000 hexademical is 1,152,912,708,553,793,536 decimal, which is as obviously within bounds.
As everybody here proposed, use BigInteger to account for such cases. For example, BigInteger bi = new BigInteger("fffff8000261e000", 16); will solve your problem. Also, new java.math.BigInteger("fffff8000261e000", 16).toString() will yield 18446735277656498176 exactly.
The number you are parsing is too large to fit in a java Long. Adding an L wouldn't help. If Long had been an unsigned data type, it would have fit.
One way to cope is to divide the string in two parts and then use bit shift when adding them together:
String s= "fffff8000261e000";
long number;
long n1, n2;
if (s.length() < 16) {
number = Long.parseLong(s, 16);
}
else {
String s1 = s.substring(0, 1);
String s2 = s.substring(1, s.length());
n1=Long.parseLong(s1, 16) << (4 * s2.length());
n2= Long.parseLong(s2, 16);
number = (Long.parseLong(s1, 16) << (4 * s2.length())) + Long.parseLong(s2, 16);
System.out.println( Long.toHexString(n1));
System.out.println( Long.toHexString(n2));
System.out.println( Long.toHexString(number));
}
Note:
If the number is bigger than Long.MAX_VALUE the resulting long will be a negative value, but the bit pattern will match the input.

Changing a String decimal (2.9) to Int or Long issues

Okay, I'm fairly new to java but I'm learning quickly(hopefully). So anyway here is my problem:
I have a string(For example we will use 2.9), I need to change this to either int or long or something similar that I can use to compare to another number.
As far as I know int doesn't support decimals, I'm not sure if long does either? If not I need to know what does support decimals.
This is the error: java.lang.NumberFormatException: For input string: "2.9" with both Interger.parseInt and Long.parseLong
So any help would be appreciated!
You can't directly get int (or) long from decimal point value.
One approach is:
First get a double value and then get int (or) long.
Example:
int temp = Double.valueOf("20.2").intValue();
System.out.println(temp);
output:
20
int and long are both integer datatypes, 32-bit and 64-bit respectively. You can use float or double to represent floating point numbers.
That string (2.9) is neither integer nor long. You should use some decimal point types, for example float or double.
Both int and long are integer values (being long the representation of a long integer that is an integer with a higher capacity). The parsing fails because those types do not support a decimal part.
If you were to use them and enforce a casting you're relinquishing the decimal part of the number.
double iAmADouble = 100 / 3;
int iWasADouble = (int)iAmADouble; //This number turns out to be 33
Use double or float instead.

Categories

Resources