3

I have a string with about 150 numbers like this String num = "64513246563........";

I am trying to add each digit of this string. So my idea was to split it into an array of ints and add them from there. I start by splitting it into a String array, then I try to convert it to an Int array. I get an unknown source error. Below is the code:

String[] strArray = num.split("");
int[] intArray = new int[strArray.length];
        for(int i = 0; i < strArray.length; i++) {
           intArray[i] = Integer.parseInt(strArray[i]);
           } 

And here is the error:

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)

Can anyone see what I'm doing wrong or is there a more efficient way of doing this?

////////////////////////////////

Thanks for your help everyone, it seems that splitting a string using .split("") creates an empty string at index 0. That was my main problem but there was lots of useful pointers on how to solve the problem more efficiently :) Thank you all for your input

1
  • print strArray[i] in each iteration of the loop and see what it prints Commented Dec 7, 2012 at 16:40

8 Answers 8

8

The first string given by num.split(""); is empty.

A solution is to simply start the iteration at index 1.

But what you do is much too expensive as you could do

    String num = "64513246563";
    for(int i = 0; i < num.length(); i++) {
         int digit = num.charAt(i)-'0';
         ... // use the digit, perhaps adding it
    } 
Sign up to request clarification or add additional context in comments.

3 Comments

+1 for showing why the empty string was there to begin with.
Exactly, I wasn't sure how I was getting an empty String. +1 and thank you for that explanation.
@shanahobo86 If this is for more than just learning, I seriously recommend you not building your intermediate array and all those strings you parse. This is really wasteful.
5
int sum = 0;
for (int i = 0; i < string.length(); i++) {
    sum += Character.getNumericValue(string.charAt(i));
}

4 Comments

You need num.length() instead of num.length.
You changed it quickly :P But you first wrote Integer.parseInt(num.charAt(i)).
@MartijnCourteaux I knew it at the time I send the answer so I changed it immediately :)
Thanks Tomas, this is what I eventually used to solve the problem :)
3
java.lang.NumberFormatException: For input string: ""

exception message clearly telling that input is empty String.

One way to handle would be, do empty String check before parsing.

 for(int i = 0; i < strArray.length(); i++) {
           if(strArray[i] != null && !"".equals(strArray[i])
              {
               int q = Integer.parseInt(strArray[i]);
              }
           } 

Note: This will still fail if input is not valid int, but not in case of empty String (or) null.

Another way to handle this would be get chartAt(i) instead of using split("")

3 Comments

This is great thanks for your help. I'm not sure how the String could be empty but this certainly handles the issue. Very much appreciated.
@shanahobo86 you can start i from 1 not zero check my answer.
@shanahobo86 Note that you will have a 0 at your 0th element in your array with this approach.
2
String num="12234";
        String[] numarr = num.split("");
        System.out.println(numarr.length);

When you split a string with "" there will be an empty string at the zeroth index. Thus your resulting array would be :

{"", "1", "2", "2", "3", "4"}

test it, the above returns the length as 6. thus Integer.parseInt("") leads to NumberFormatException.

Test:

String num="12234";
        String[] numarr = num.split("");
        for(String s: numarr){
            if(s.equals("")){
                System.out.println("empty string");
            }
            else {
                System.out.println(s);
            }

Output:

empty string
1
2
2
3
4

Thus, there is an emptyString at index 0.

so, you will have to check if the String is an empty string before parsing it:

String[] strArray = num.split("");
int[] intArray = new int[strArray.length];
        for(int i = 0; i < strArray.length; i++) {
           if(!strArray[i].equals(""))
           intArray[i] = Integer.parseInt(strArray[i]);
           } 

1 Comment

Thank you for the detailed explanation. I won't make the same mistake again:) +1
1
char[] charArray = num.toCharArray();

for(char c : charArray) {
    int q = Integer.parseInt("" + c);
} 

Comments

0
for(int i=0; i<yourString.length; i++) {
    yourIntegers[i] = Integer.parseInt(yourString.charAt(i).ToString());
}

Comments

0

I'd simply step along the string, parsing each digit:

int sum = 0;
for (int i = 0; i < num.length(); ++i) {
    sum += Integer.parseInt(num.substring(i, i + 1));
}

Comments

0

Since array start from a empty string you have to skip first element hence Start i from 1 in your for loop.

for(int i = 1; i < strArray.length; i++)

1 Comment

A rationale would improve this answer.

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.