I'm trying to convert a String to an Integer. I have the following code:
List<String> strings = populateSomeStrings();
List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < strings.size(); i++) {
ints.add(Integer.valueOf(strings.get(i)));
}
When I run it I get an exception saying:
java.lang.NumberFormatException: Invalid int: "1000"
Any ideas why this would be happening? I also tried Integer.parseInt but it does the same thing.
Thanks
There's obviously something in your strings that isn't numeric.
Catch the exception and print out the string length and code points for each character, using codePointAt for example.
That should tell you what's wrong.
Related
This is just a little bit of my code, but I am trying to loop through two strings, get the value of the first number in one string, and then use that number as the position to find in the other string, then add that word into a new string. But it comes up with the error "String cannot be converted to int" can anyone help?
String result = "";
for (int i = 0; i < wordPositions.length; i++){
result += singleWords[wordPositions[i]];
}
if your wordPositions is a String array when you do this:
result += singleWords[wordPositions[i]];
it like if you does this
result += singleWords["value of the wordPositions array at index i"];
but is need to be an int in [] not a string that why you have the exception String can not be cast to Int
If wordPositions is an array of numbers inside a string for example
String[] wordPositions = new String[]{"1","2","3"};
Then you nees to use
Integer.parseInt(NUMBER_IN_STRING);
To change the string value to an int value.
You are getting this error because wordPositions[i] returns a string and you need to convert it to int before trying to acess singlewords[].
result += singleWords[Integer.parseInt(wordPositions[i])];
Use this to convert String into int
Integer.parseInt(integerString);
The completed line of code:
result += singleWords[Integer.parseInt(wordPositions[i])];
I am working at converting string number into binary. But Eclipse throws a NumberFormatException. Can I ask you, to look at my code? I have no idea what is wrong..
public float liczbaF(String lancuch){
float array [] = new float [31];
float liczba;
double mantysa;
int znak;
long cecha;
char element[] = new char[22];
String temp="";
if (lancuch.charAt(0)=='1')
znak=-1;
else
znak=1;
for(int i=1;i<8;i++)
{
element[i-1] = lancuch.charAt(i);
}
temp=String.valueOf(element);
System.out.println(temp);
cecha=Integer.parseInt(temp,10);
cecha=cecha-127;
System.out.println(cecha);
for(int i=31;i>9;i--)
{
element[31-i] = lancuch.charAt(i);
}
temp=String.valueOf(element);
mantysa=(((Integer.parseInt(temp,10))/(pow(2,22)))+1);
liczba=(float)(mantysa*pow(2,cecha));
return liczba;
}
It throws:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1001101
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Konwersja.liczbaF(Konwersja.java:30)
at Main.main(Main.java:10)
I will be grateful for any help.
Thank you
Your element array is 22 long:
char element[] = new char[22];
but you only fill in the first 7 elements:
for(int i=1;i<8;i++)
{
element[i-1] = lancuch.charAt(i);
}
So there are null characters at the end of the string, which make it unparseable as an integer.
This works better:
temp=String.valueOf(element,0,7);
I would recommend using a StringBuilder to add characters to a String, not a char array.
The reason for NumberFormatException is the hidden characters of element array. element array has a length of 22 but only filled by first few characters. So the rest are '\u0000'. An easy solution is:
modify this line:
temp=String.valueOf(element);
to:
temp=String.valueOf(element).trim();
In my program I need to convert a String to Int.
String str = new String(request.getData());
String [] setting = str.split(" ");
String bs = setting[1];
The value of bs is 1024, I use System.out.println to test it, and it displays on the screen with "1024".
But when I use
int blockSize = Integer.parseInt(bs);
it will return an exception point to the line of Integer.parseInt :
Exception in thread "main" java.lang.NumberFormatException: For input string: "1024"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.valueOf(Integer.java:554)
Can someone help me to solve it? Thanks.
I suspect you have some hidden unicode character in the string bs, you can remove the non-digits with:
bs = bs.replaceAll("\\D", "");
int blockSize = Integer.parseInt(bs);
The code above will also convert the string "1a2" to 12, but that doesn't seem your case.
try this code:
String bs = setting[1].trim().toString();
while( (!bs.matches("\\d+")) && (bs.length > 1))
{
bs = bs.substring(1);
}
if (bs.matches("\\d+")
{
int blockSize = Integer.parseInt(bs);
}
else
{
int blockSize = -1;
}
/* !! Then, check for "-1" in your application of
block size #runtime_exception_prevention */
This will continue to remove the offensive non digit bits down to 1, as necessary, until a digit is found or only one character remains in the string. The second check prevents the exception and returns a flagged value. Checking for this flagged value will intercept runtime exceptions.
NB: I wrote this code in the comment block, please forgive any minor errors, I will gladly correct.
I need to get textbox value into array and convert them into integer.
I'm not sure whether should I 1st convert and get into array or get into array and after convert.
Please explain with relevant examples
I've already tied out this code segment. But its wrong according to my knowledge.
String data [] = Integer.parseInt(jTextField1.getText());
String[] stringValues = jTextField1.getText().split("[,]");
int[] numArray= new int[stringValues.length];
for(int i=0; i<numArray.length; i++){
numArray[i]= Integer.parseInt(stringValues[i]);
}
You are trying to assign an single inter to a string array so it will not work.
Because two types are incompatible.
Either you must have an integer array or you can have string array and use string value of the textfield.
e.g.
String []stringData = {jTextField1.getText()};
or
int [] = {Integer.parseInt(jTextField1.getText())};
But since you are using just single value it is better to use an variable rather than an array.
Try this:
String str = "34,56,78,32,45";
String[] parts = str.split(",");
for (int i = 0; i < parts.length; i++)
{
int no=Interger.parse(parts[i]);
//Do your stuff here
}
I'm parsing a doc and I get the following error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Float.valueOf(Float.java:388)
at CentroidGenerator$Centroid.averageLat(CentroidGenerator.java:403)
at CentroidGenerator.getCentroids(CentroidGenerator.java:30)
at CentroidGenerator.main(CentroidGenerator.java:139)
This is the part of code throwing the exception:
if (latitude!=null) {
//if (!latitude.equals("null")) {
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
latitude = Float.toString(sum / (float) latValues.length);
//}
}
As you can see I've tried to check for "null" strings but even uncommenting the second if statement I get the same error.
thanks
Maybe one of the values is "null" (for example, the string : "123.4 null 5 null") not the first one, so I think a proper solution will be:
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
if (!latValues[i].equals("null"))
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
latitude = Float.toString(sum / (float) latValues.length);
or instead, add try-cath inside the for loop and ignore values that are not numbers.
EDIT
As pointed in comments (Sualeh), it is better to use try / catch because today it's "null" tomorrow it's something else (i.e. double spaces...).
try {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
catch (NumberFormatException e)
{
// log e if you want...
}
To avoid issues with strings like "1 2", with multiple spaces, which give null values, it is best to add a try-catch inside the loop, like this:
if (latitude != null) {
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
try {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
latitude = Float.toString(sum / (float) latValues.length);
}
It is pretty clear that the problem is that you have an input line that has the characters "null" instead of one of the numbers. But I don't think that ignoring the nulls is necessarily the right thing to do.
First, you need to figure out what those nulls really mean:
Do they denote missing data-points (latitude values)?
Are they a symptom of a bug in the code that captured the original latitude data?
are they a symptom of a bug in the code that read the data from an input file / database?
Then maybe you need to track down the bug / bugs or adjust your processing to deal with the missing data.
Based on your error, it is very possible your latValues[i].trim() displays the value "null". I'm able to replicate your problem here:-
Float.valueOf("null");
Here's the stacktrace:-
java.lang.NumberFormatException: For input string: "null"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1301)
at java.lang.Float.valueOf(Float.java:375)
In another word, the value you have is not null, but it contains the word "null".
If you do Float.valueOf(null);, that actually gives you a NullPointerException, which is not what you have here.
The call of the trim function is useless. If you really want to screen your input data to avoid the NumberFormatException you find the code in the JavaDocs for Doubles
The parseInt() and parseDouble() will error with NFE if passed with a null, space or blank string value. Once you have handled the null condition it will still fail with an empty string. Try adding a zero before the empty string like below. It maintains the integrity of calc as well:
Integer.parseInt(" ".trim())
to
Integer.parseInt( "0" + " ".trim())