1

I have a string array which is filled with numbers. Any unset element in the array will be null by default. I'm then looping through this array, parsing the Strings to their int values, but I'm running into a NumberFormatException when the loop reaches a null element.

I don't know in advance how many numbers will be in the array, so I'm using a large array to make sure there is enough space to hold all of the Strings.

How can I stop the loop before it reaches a null element?

for (int x = 1 ; x < array1.length ; x++){
    int newnode = Integer.parseInt(array1[x]);
    //searching in matrix
    // do other stuff
}
JonK
  • 2,097
  • 2
  • 25
  • 36
Bahare Mkh
  • 41
  • 4

2 Answers2

1

If you don't know the number of elements that you will be handling in advance each time, then use a dynamically-sized collection instead of a fixed-size array.

Change the code that populates your collection to use a List<String> instead of a String[]. Lists are dynamically-sized, and will continually grow as you add more elements to it. There won't be any null elements returned when you iterate unless you specifically add them in the first place, so your code will never attempt to parse a null value.

This change would then allow you to iterate over the List like so:

for (String number : array1) { // You might want to rename array1 to something meaningful...
    int newNode = Integer.parseInt(number);
    // Do other stuff
}

You can still maintain a separate index variable if you need to do so, it would just be declared and incremented manually, rather than as part of the loop construct.

JonK
  • 2,097
  • 2
  • 25
  • 36
  • A try catch block should be used around `Integer.parseInt()` because it can throw `NumberFormatException` for many reasons and you probably don't want the program to halt then. – Michael Shopsin Nov 12 '15 at 20:40
  • 1
    @MichaelShopsin That depends on the contents of the list. If you have control over the source and the code that creates the list you can ensure that only valid data is inserted into it in the first place. In that instance, you could argue that a failure at this point is indicative of a more fundamental error earlier in the code. It also may indicate that the data is in an invalid state and that processing should not continue further. If invalid data can be ignored, then by all means catch the exception and continue processing...if it can't, don't. – JonK Nov 12 '15 at 20:45
  • Nov In my experience `Integer.parseInt()` is that it's overly sensitive so I usually catch the exception and then try to parse the number another way. – Michael Shopsin Nov 16 '15 at 16:44
  • @MichaelShopsin But if you've ensured that the data is valid at point of entry, then catching the NFE later on is as good as dead code. I prefer when possible to reject the bad data quickly, rather than let it live in the application to fail at some unknown point later on. – JonK Nov 16 '15 at 16:50
  • Sometimes I'm reading a file or other input where I do not get to control what is coming in, and don't want to stop the whole input on every single error. When I read a series of XML files I don't want to stop on a single number error since they will not make an important difference to the results. There was a good discussion in [How to avoid Number Format Exception in Java](http://stackoverflow.com/a/19749081/369446) about fully validating numbers in strings. – Michael Shopsin Nov 16 '15 at 17:00
  • @MichaelShopsin Oh it's certainly not something that is always possible to do - I'm not claiming that. As with all things in code, the best solution depends on your use-case; sometimes you need to catch the exception, sometimes you don't. It's for the OP to decide if that's required for their particular scenario – JonK Nov 16 '15 at 17:05
-1

i think this is true :

for (int x = 1 ; x < array1.length ; x++){
    int newnode = -1;
    if(array1[x].equals("")) 
        break;
    try{
        newnode = Integer.parseInt(array1[x]);
    }catch(NumberFormatException e){
        System.err.println("err");
    }
    //searching in matrix
    // do other stuff
}
Clark Kent
  • 1,178
  • 1
  • 12
  • 26
Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25
  • There are far better solutions to avoid this problem than try-catch – JonK Nov 12 '15 at 16:30
  • @JonK my solution is not wrong , so i can't understand why are you downvote my answer :? – Mohsen_Fatemi Nov 12 '15 at 16:34
  • See my first comment. It may well work, but that doesn't mean it's a *good* solution. – JonK Nov 12 '15 at 16:35
  • @JonK and it doesnt enough reason to downvote , admit it – Mohsen_Fatemi Nov 12 '15 at 16:37
  • @JonK if u have better solution write it , if you don't write it , my solution is better than your IMAGINARY solution , write it and i will upvote it – Mohsen_Fatemi Nov 12 '15 at 16:40
  • Why are you capturing the entire loop with a `try` statement, and catching `Exception` instead of `NumberFormatException` ? – Clark Kent Nov 12 '15 at 16:41
  • @SaviourSelf Exception e in itself have all of exceptions like numberformatexception , arrayindexoutofbound , ... – Mohsen_Fatemi Nov 12 '15 at 16:43
  • That's what i was wondering.... Using the try on the entire loop can catch other exception also like ArrayIndexOutOfBounds exception..and so on – Doc Nov 12 '15 at 16:44
  • 1
    If that's the case, you could wrap the whole program in a try catch. I think that's bad form, and doesn't help the OP to understand exception propagation. – Clark Kent Nov 12 '15 at 16:46
  • 1
    So you won't know what kind of exception raised the flag. It is always the best option to be very precise while specifying the type of exception in the catch block.. – Doc Nov 12 '15 at 16:46
  • @SaviourSelf i know that , his question was about try catch and i answered it with try catch – Mohsen_Fatemi Nov 12 '15 at 16:48
  • Another issue is that your `if (array1[x].equals("")) break;` check isn't null-safe. It also won't help in this instance - the OP stated that the elements that don't contain numbers are `null`, so you'll immediately hit a `NullPointerException` when evaluating that condition instead of a `NumberFormatException` later on. All you're doing is trading one exception for another. – JonK Nov 12 '15 at 16:49
  • @shivam7357 the question was about try catch and i answered it with try catch , i know it has better solutions – Mohsen_Fatemi Nov 12 '15 at 16:49
  • @Mohsen_Fatemi well u should use this type of try-catch block which doesn't kill the complete loop for (int x = 1 ; x < array1.length ; x++){ if(array1[x].equals("")) break; try{ int newnode = Integer.parseInt(array1[x]); //searching in matrix // do other stuff }catch(Exception e){ System.out.println("err"); } } – Doc Nov 12 '15 at 16:50
  • @shivam7357 ok , forgive me , i havent enough time to write all of those – Mohsen_Fatemi Nov 12 '15 at 16:52