title: Casting IllegalArgumentException for this program
body: <p>So I am doing a code that converts a string to an array. What is left is basically is to make the code throw the exception IllegalArgumentException
  for the last 4 strings you put into the str2ia method. </p>
  
  <p>I can successfully get the code to crash or stay on an infinite loop when trying to make this happen. </p>
  
  <p>And honestly I am sure there is something obvious that I can't see  </p>
  
  <pre><code>import java.util.Arrays;
  
  
  import java.util.Scanner;
  
  public class String2intArray {
  
  public static void main(String[] args) {
      System.out.println(Arrays.toString(str2ia("6,8 ,9 , 10")));
      System.out.println(Arrays.toString(str2ia("1002")));
      System.out.println(Arrays.toString(str2ia("")));
      System.out.println(Arrays.toString(str2ia(", 2")));
      System.out.println(Arrays.toString(str2ia("Ett,Två")));
      System.out.println(Arrays.toString((str2ia("1,,2"))));
      System.out.println(Arrays.toString(str2ia("1 , 2 ,")));
  
  
  }
  public static int[] str2ia(String s) {
      int arraylengt = 0;
      int arrayindex = 0;
      Scanner scan = new Scanner(s).useDelimiter(" *, *");
      if(s.length() == 0)
      {
          int[] emptyArray = {};
          System.out.print("empty array ");
          return emptyArray;
      }
      while (scan.hasNext()) {
          if (scan.hasNextInt()) {
              int nextInt = scan.nextInt();
  
              arraylengt ++;
          } else {
              // discard next token
              scan.next();
  
          }
      }
  
       int[] intArray = new int[arraylengt];
  
      Scanner scan2 = new Scanner(s).useDelimiter(" *, *");
      try {
          while (scan2.hasNext()) {
              if (scan2.hasNextInt()) {
                  intArray[arrayindex] = scan2.nextInt();
                  arrayindex++;
  
              } else {
                  // discard next token
                  throw new IllegalArgumentException("Bad input");
              }
  
              }}
          catch (IllegalArgumentException e) {
              System.out.print("Bad input");
              int[] emptyArray = {};
              return emptyArray;
  
          }
  
      {
  
      return intArray;
  
             }
  
            }
               } 
  </code></pre>