Converting a string array to a large number array - java

So, in Java I have a large number in the command argument, let's say 12345678910, and I cannot use bigInteger, and I already did:
String[] g = args[1].split("");
So, my string is put in a string array. But, I cannot use:
int[] ginormintOne = new int[g.length];
for(int n = 0; n < g.length; n++) {
ginormintOne[n] = Integer.parseInt(g[n]);
}
It gives me this:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Ginormint.main(Ginormint.java:67)
I think my numbers are too large for int. Any idea on how to convert it to a large number array?

You are splitting on an empty string. For example,
"123 456".split("")
results in this array:
["" "1" "2" "3" " " "4" "5" "6"]
This is where your exception comes from.

The first element of the array from args[1].split("") is an empty string that to my opinion causes the exception java.lang.NumberFormatException since it cannot be converted to an Integer

Use Long.parseLong instead of Integer.parseInt and a long[] instead of Long.parseLong.
But that said, the NumberFormatException indicates the failure is because you're passing it an empty string. Are you sure you're splitting the string correctly, or that splitting is even necessary? The args array in main is already split on spaces, assuming that's where args is coming from.

Related

number format exception when trying to parse a string

I want to convert Integer.MAX_VALUE to binary and want the represenation to be of type int. I passed it to Integer.tobinarystring() and wraped that with Integer.parseint but i get numberformatexception.
Here is the code
System.out.println(
Integer.parseInt(
Integer.toBinaryString(Integer.MAX_VALUE)
)
);
Here is the exception
Exception in thread "main" java.lang.NumberFormatException: For input string: "1111111111111111111111111111111"
Integer.MAX_VALUE is 2,147,483,647
In binary this is:
1111111111111111111111111111111
If we treat that like an integer again, which is 1,111,111,111,111,111,111,111,111,111,111 you can probably see that it is much larger than the max value.
You probably want to look into BigInteger if you really need to deal with that as a int.
If you want to get the integer value of the binary string
1111111111111111111111111111111
you must use another signature of parseInt() that takes as 2nd parameter the radix, in this case of a binary string the radix is 2
String str = Integer.toBinaryString(Integer.MAX_VALUE);
int number = Integer.parseInt(str, 2);
System.out.println(number);
it will print:
2147483647

Hex String reading for hash function in java not working

I'm doing a project and i have a really simple hash function in java that SHOULD read each "data" (which is a generic type that is a String or Double type read by file) character and make a sum of their values that will be used as hashcode.
I thought that i could convert each character to Hexadecimal, and then "decode" or "parseInt" the obtained String, but it does not work and i do not understand why.
Here is my method:
public long HashFunction(T data){
String bytes = data.toString();
int value=0;
for (int i=0; i<bytes.length(); i++)
value = value + Integer.decode(Integer.toHexString( bytes.charAt(i) | 0x100000).substring(1));
return (value%1583)%(size);
//1583 prime number not near to the power of 2, size is the size of the array of my hashtable
}
And here is my error, 0038 should be an "8":
Exception in thread "main" java.lang.NumberFormatException: For input string: "0038"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at java.lang.Integer.decode(Unknown Source)
at dizionario_package.HashTable.HashFunction(HashTable.java:22)
at dizionario_package.HashTable.HashInsert(HashTable.java:29)
at dizionario_package.RecordReader.CreateHTFromFile(RecordReader.java:24)
at dizionario_package.proviamo.main(proviamo.java:8)
Also, i'm sure that the error is in this function, because if i use the java hashcode method, it works.
Thanks in advance.
You need to tell decode you're using hex. Prefix the string with 0x.
value = Integer.decode("0x"+"10038".substring(1));

Check if number is too large or not a number

I am trying to parse a string safely,
public <T> long safeParseLong(T s){
try {
return Long.parseLong(s.toString());
}catch (NumberFormatException e){
return 0;
}
}
This will always work and if the string is not parsable, it will return 0.
However, is there a way to know what the reason is for it to be unparsable? Specifically, I want to know if it is not a number at all ("foo") or the number is too large (≥ 9223372036854775808).
The Long.parseLong method will throw a NumberFormatException if the string isn't a number or if the number wouldn't fit in a long.
If the exception is thrown, then test whether the string fits the regular expression for a number, "[+-]?[0-9]+". If it matches, it's a number that couldn't fit in a long. If it doesn't match, then it wasn't a number at all, e.g. "foo".
boolean isNumber = s.toString().matches("[+-]?[0-9]+");
But you are returning 0 if there was an error. This is indistinguishable from if the content of the string were "0". Perhaps it would be better to let an exception be thrown from this method. But instead of a NumberFormatException, you could create and throw a NotANumberException if it's not a numeric string, or a NumberMagnitudeTooLargeException if the parsing failed because it's too large to fit in a long.
Unfortunately, Long.parseLong will throw NumberFormatException in any case.
Long.parseLong(new String(new BigInteger(Long.toString(Long.MAX_VALUE)).add(new BigInteger("1")).toString()));
results in:
Exception in thread "main" java.lang.NumberFormatException: For input string: "9223372036854775808"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at java.lang.Long.parseLong(Unknown Source)
at Main.main(Main.java:13)

Java Fractions, again

Yesterday, I attempted to do this one way...today I am trying another and I am still stuck. I have to find a way of doing this using integer division and mod. Here is my code followed by the error messages.
public int evaluateFraction(int w, int n, int d)
throws NumberFormatException
{
whole = w;
numerator = n;
denominator = d;
return portion2;
}
Tester
input = JOptionPane.showInputDialog("Enter");
portion2 = Integer.parseInt(input);`
error messages:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1 1/8"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at ClientCode.main(ClientCode.java:43)
Java Result: 1
What on earth am I doing wrong now?
Integer.parseInt is able to parse only valid integer strings. If the input string contains anything other than digits then it will throw NumberFormatException.
You are trying to parse an expression 1 1/8, which is not a valid integer string.
"1 1/8" is not a number. 1 and 8 are, whitespace and / are not. You need to parse such expression by hand.
1 1/8 is not an integer, Integer.parseInt can perform well in the only one case, if data is valid.
Don't know, what result you expect but you either need some other method or parse it yourself.

Converting from hex to int in java

I am getting an error because of the following line of code:
int x = color(Integer.parseInt("ffffffde",16));
I think it might be because it is a minus value
Any ideas why or how or how to fix it?
EDIT:
Sorry, didn't include the actual error. here it is:
Exception in
thread "Animation Thread" java.lang.NumberFormatException: For input
string: "ffffffde" at
java.lang.NumberFormatException.forInputString(Unknown Source) at
java.lang.Integer.parseInt(Unknown Source)
EDIT 2:
The value ("ffffffde") is being created by the following code:
Integer.toHexString(int_val);
EDIT 3:
Turns out it is a known bug (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269)
Although you can convert integers to hex strings, you cannot convert them back if they are negative numbers!!
ffffffde is bigger than integer max value
Java int is 32 bit signed type ranges from –2,147,483,648 to 2,147,483,647.
ffffffde = 4,294,967,262
Edit
You used Integer.toHexString(int_val) to turn a int into a hex string. From the doc of that method:
Returns a string representation of the integer argument as an unsigned integer in base 16.
But int is a signed type.
USE
int value = new BigInteger("ffffffde", 16).intValue();
to get it back as a negative value.
If you are getting error like this,
Exception in thread "main" java.lang.NumberFormatException: For input string: "ffffffde"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:461)
at com.TestStatic.main(TestStatic.java:22)
Then there is problem with value you are passing that is ffffffde . This is not a valid hex value for parsing to int.
Please try this
int x = Integer.parseInt("ffffde",16);
System.out.println(x);
It should work.
For hex values more than that you have to pars to Long
Long x = Long.parseLong("ffffffde",16);
System.out.println(x);
And this also should work

Categories