0

a little help here. I'm so confused and have done so many variations of converting String array into int array.

I get numbers from a file then tokenize it. However, I get a NumberFormatException and a lot of errors when trying to convert the array. Any idea?

Here's my code below:

int[] intarray=new int[token.length];
    int i=0;
    for (String str : token){
        intarray[i++] = Integer.parseInt(str);
    }

Any help would be much appreciated.

[EDIT] When I do this code below. No errors but it only prints some integers in the token.

int[] ints = new int[arrays.length];
for(int i=0; i<array.length; i++){
  try{
    ints[i] = Integer.parseInt(array[i]);
  }
  catch(NumberFormatException nfe){
    //Not an integer, do some
  }
}

Here's the txt file where I get the numbers:

3 5
1 2 1
2 4 2
3 1 2
6 2 3
4 9 1

[SOLVED] I got it. Simply split("\W+"). I thought splitting " " is enough to also split newline. Thanks guys.

2
  • 1
    Post your file content Commented Jan 29, 2014 at 6:47
  • 1
    The problem is not in the code you posted, you need to post the code you're using to populate your tokens Commented Jan 29, 2014 at 6:50

6 Answers 6

2

Probably str doesn't represent an int. See the docs - ... NumberFormatException - if the string does not contain a parsable integer.

To know your problem, you can do the following:

int[] intarray=new int[token.length];
int i=0;
for(String str : token){
   try {
       intarray[i++] = Integer.parseInt(str);
   } catch(NumberFormatException e) {
       System.out.println(str + " is not a parsable int");
     }
}
Sign up to request clarification or add additional context in comments.

2 Comments

` is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int is not a parsable int`
Then you have this amount of unparsable ints. They are probably some empty Strings.
2

The best way is to make sure your str represent ints only, by removing all non-digit character:

for (String str : token){
    if(str.replaceAll("\\D","").length()>0)
        intarray[i++] = Integer.parseInt(str.replaceAll("\\D",""));
}

By the way, if white-spaces is the only possible non-digit characters to exist in your array, you can simply use str.trim()

2 Comments

This can still result in a NumberFormatException if the value is too large for an int.
I assume there is no big number, referring to the sample above
0

Hi i am fully agreed with @maroun but if you say you are passing only numeric value in token array then use the trim because sometime we do not take care of space before and after..

like if you try to convert

" 123 " to int it will throw error because of extra space

so i will suggest you to also use the trim() when u are parsing the string to int

intarray[i++] = Integer.parseInt(str.trim());

Comments

0

You can get a NumberFormatException if you are reading even the spaces from your input. Please make sure that you trim your string before Integer.parseInt also check whether the string represents an integer

Comments

0

I face the same problem but in my case string contains only number.and if your token contains only number value then you can try with

int[] intarray=new int[token.length];

int i=0;

for (String str : token) {

intarray[i++] = Integer.valueOf(str);

}

2 Comments

i dont think replacing parseInt by valueOf will resolve the issue.. read it again
Integer.valueOf(str) internally calls Integer.parseInt(str)
0

The problem is in the way you're getting the strings from your file. Try this function to get your array of strings:

String[] getTokens(String filename) {

    try {
        String line;
        StringBuilder fileInAStringBuilder = new StringBuilder();
        BufferedReader fileReader = new BufferedReader(new FileReader(filename));
        while((line = fileReader.readLine()) != null) {
            fileInAStringBuilder.append(line).append(' ');
        }
        String fileInAString = fileInAStringBuilder.toString();
        fileInAString = fileInAString.replaceAll("\\D", " ");

        fileReader.close();

        return fileInAString.split(" +");

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

Your code would be something like this:

String[] token = getTokens("myFileName.txt");

int[] intarray=new int[token.length];
int i=0;
for (String str : token){
    intarray[i++] = Integer.parseInt(str);
}

Be also aware that this could fail if any of numbers is too big to "fit" in an int.

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.