waltermilner

Untitled

Sep 25th, 2017
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1.  
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. public class Test {
  6.  
  7.   public static void main(String[] args) {
  8.     // test data
  9.     String[] t = {"    22 20 23 ", "50 56", "a b c", "1 2 3", "1 -2 3", " "};
  10.     List<Integer> list = convert(t); // convert it
  11.     for (Integer i : list) // check
  12.     {
  13.       System.out.println(i);
  14.     }
  15.     /*
  16.      java.lang.NumberFormatException: For input string: "abc"
  17.      java.lang.NumberFormatException: For input string: "1-23"
  18.      java.lang.NumberFormatException: For input string: ""
  19.      222023
  20.      5056
  21.      123
  22.      */
  23.  
  24.   }
  25.  
  26.   static List<Integer> convert(String[] values) {
  27.     // make empty list of Integer
  28.     List<Integer> list = new ArrayList<>();
  29.     for (String s : values) // each array element
  30.     {
  31.       String temp = s.replaceAll(" ", ""); // remove spaces
  32.       try {
  33.         int i = Integer.parseInt(temp); // change to an int
  34.         list.add(i); // put in list - uses autoboxing - Integer not int
  35.       } catch (NumberFormatException nfe) // in case not valid integer
  36.       {
  37.         System.out.println(nfe);
  38.       }
  39.     }
  40.     return list;
  41.   }
  42.  
  43. }
Advertisement
Add Comment
Please, Sign In to add comment