1

I'm trying to process a file with a variety of strings. Ultimately I'm interested in the numbers contained in the file, and want to disregard everything else. Some of the numbers will have "$" in front of them. I still want to include these numbers, but am not sure of the optimal way to do it.

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(new File("asdf.txt"));
    while (input.hasNext()) {
         if (input.hasNextInt()) {
             process(input.nextInt());
         } else {
             processString(input.next());
         }
    }
}

public static void processString(String phrase) {
     if (phrase.startsWith("$")) {
         phrase = phrase.substring(1);
         try {
             int number = Integer.parseInt(phrase);
             process(number);
         } catch (NumberFormatException e) {
         }
     }
}

public static void process(int number) {
    // ... foo ...
}

This a simplified version of what I have, and my full version works. I want to avoid using try/catch statement inside of processString and was wondering if there was a more elegant way of accomplishing this.

  • There are a variety of libraries that can tell if a given string is numeric. See http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java – alexgbelov Aug 10 '16 at 22:44
  • 4
    If your code *works fine* and you are looking for potential ways to improve it http://codereview.stackexchange.com/ would be better fit for your question than Stack Overflow (which is about fixing problems rather than improvement). – Pshemo Aug 10 '16 at 22:44
  • Can you provide a simple file entry. Maybe you can write a custom delimiter for `Scanner` that will work on both types of numbers. – Janez Kuhar Aug 11 '16 at 00:09

0 Answers0