Advertisement
brilliant_moves

TestIntegers.java

Jan 13th, 2015
441
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.05 KB | None | 0 0
  1. public class TestIntegers {
  2.  
  3.     /**
  4.     *   Program:    TestIntegers.java
  5.     *   Purpose:    Remove non-integer tokens from a string.
  6.     *   Creator:    Chris Clarke
  7.     *   Created:    13.01.2015
  8.     */
  9.  
  10.     public static boolean findError(String token) {
  11.         int n;
  12.         boolean error=false;
  13.         try {
  14.             n = Integer.parseInt(token);
  15.         } catch (NumberFormatException e) {
  16.             error=true;
  17.         } // try..catch
  18.         return error;
  19.     } // test
  20.  
  21.     public static void main(String[] args) {
  22.         String testString = "1 2 three 4 5 6 seven 8 9 10";
  23.         String result = "";
  24.         String[] theStrings = testString.split(" ");
  25.         int errorCount=0;
  26.         for (String s: theStrings) {
  27.             if (findError(s)) {
  28.                 System.out.println(s + " is not a number.");
  29.                 errorCount++;
  30.             } else {
  31.                 System.out.println(s + " is a number.");
  32.                 result += s+" ";
  33.             } // if
  34.         } // for
  35.         System.out.println("In the string \"" + testString + "\",");
  36.         System.out.println("there were "+errorCount+" items which were not numbers.");
  37.         System.out.println("They've been removed: "+result);
  38.     } // main()
  39.  
  40. } // class TestIntegers
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement