package mode.problem; import java.util.*; /** * * @author Daniel Ruess */ public class ModeProblem { /** * @param args the command line arguments */ public static void main(String[] args) { List nums = new ArrayList(); Scanner in = new Scanner(System.in); while (true) { System.out.print("Enter a number (enter M to find the mode): "); String n = in.next(); if (n.equalsIgnoreCase("M")) { int[] mode = findMode(nums); System.out.println("The mode of the number set is " + mode[0] + " with a frequency of " + mode[1]); return; } else { for (char c : n.toCharArray()) { if (!Character.isDigit(c)) { System.err.println("Invalid input: " + n); return; } } nums.add(Integer.valueOf(n)); } } } static int[] findMode(List vals) { Map map = new HashMap(); for (Integer i : vals) { if (map.get(i) == null) { map.put(i, 1); } else { map.put(i, map.get(i) + 1); } } int mode = -1, v = 0; for (Integer i : map.keySet()) { if (map.get(i) > v) { mode = i; v = map.get(i); } } return new int[] { mode, v }; } }