Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mode.problem;
- import java.util.*;
- /**
- *
- * @author Daniel Ruess <mistermaggot@gmail.com>
- */
- public class ModeProblem {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- List<Integer> nums = new ArrayList<Integer>();
- 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<Integer> vals) {
- Map<Integer, Integer> map = new HashMap<Integer, Integer>();
- 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 };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement