0

Assumptions:

  1. Each String in the String Array is type Double.

  2. Some Strings in the String Array may be null.

  3. 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.

2
  • 2
    It would help if you showed the code you have so far. Commented Dec 31, 2012 at 14:04
  • 1
    Without the code of your problem, you doesn't seems Code Enthusiastic.!! Commented Dec 31, 2012 at 14:10

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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 + " ");
            }
        }
    }

Comments

2

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(".")));
    }
}

Comments

2

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.