Question:
Design and implement a program that counts the number of integer values in a text input file.
Code:
import java.util.*; import java.io.*; public class CountNumbers { public static void main(String[] args) { try { File f = new File("numbers.txt"); Scanner scanner = new Scanner(f); int total = 0; System.out.println("Numbers:"); while(scanner.hasNext()) { String str = scanner.next(); if(isInteger(str)){ System.out.println(str); total++; } } System.out.println("Total: " + total); } catch(Exception e) { } } public static boolean isInteger(String input) { try { Integer.parseInt(input); return true; } catch (NumberFormatException e) { return false; } } }
Output:
$ java CountNumbers Numbers: 1 2 3 4 5 6 7 8 9 Total: 9 $ cat numbers.txt 1 2 3 word 4 5 word 6 word 7 word word word word 8 word word string string This is a test 9 the end