Reputation: 2847
Assumptions:
Each String in the String Array is type Double.
Some Strings in the String Array may be null.
Whenever a string in String Array is null, its corresponding Integer in Integer Array should have a value of 0.
Edit: After converting successfully I want to return this created Integer Array.
I am stuck in the places where Strings are null, getting NumberFormatException in the places where Strings are null.
Thanks in Advance.
Upvotes: 0
Views: 187
Reputation: 2068
So you want to convert your Strings to Integers even though they store doubles? If so then something like this should work:
for (int i = 0; i < stringArray.length; i++) {
String s = stringArray[i];
if (s == null || s.isEmpty()) {
integerArray[i] = new Integer(0);
} else {
integerArray[i] = new Integer(s.substring(0,s.indexOf(".")));
}
}
Upvotes: 2
Reputation: 2555
Hope this helps!
public class Test {
public static void main(String[] args) {
String[] strArray = {"1.1", "2.2", null, "3.3"};
Integer[] intArray = new Integer[4];
for (int i = 0; i < strArray.length; i++) {
intArray[i] = (strArray[i] == null) ? 0 : (int) Double.parseDouble(strArray[i]);
}
System.out.println("String array = ");
for (String str : strArray) {
System.out.print(str + " ");
}
System.out.println();
System.out.println("Integer array = ");
for (Integer integer : intArray) {
System.out.print(integer + " ");
}
}
}
Upvotes: 3
Reputation: 2887
A simple ternary operator will do it:
String[] s = //Array instantiation
double d = new double[s.length];
for(int i = 0; i < s.length; i++)
{
d[i] = s[i] == null ? 0 : Double.parse(s[i]);
}
Upvotes: 2
Reputation: 51445
Before you convert the String to Double, you use an if statement to check if the String is equal to null.
If the String is equal to null, move zero to the Integer array, else do the String to Double conversion, convert the Double to an Integer, and put the Integer in the Integer Array.
Upvotes: 3