sábado, 1 de maio de 2010

Java - Convertendo um array de String para um array de Int

Digamos que você tem um array de Strings, só que este array de String na verdade só tem números no formato String dentro dele. Você pode converter este array de Strings em um array de int de forma fácil. É só usar este método abaixo:


   public static int[] convertStringArrayToIntArray(String[] s) {
      try {
         int[] intArray;
         try {
            intArray = new int[s.length];
         } catch (NullPointerException e2) {
            return null;
         }
         for (int i = 0; i < s.length; i++) {
            try {
               intArray[i] = Integer.parseInt(s[i]);
            } catch (Throwable e) {
               try {
                  if (s[i].equals("")) {
                     intArray[i] = 0;
                     continue;
                  }
               } catch (NullPointerException e1) {
                  intArray[i] = 0;
                  continue;
               }
               throw e;
            }
         }
         return intArray;
      } catch (Throwable e) {
         throw new RuntimeException(
                  "JavaUtils.convertStringArrayToIntArray() - Error on convert the String array \"" +
                           s + "\" to an int array. Error details: " + e);
      }
   }

Nenhum comentário: