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.