import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class CubeProbability { @SuppressWarnings("unchecked") public static void main(String args[]){ HashMap cubeResult = new HashMap(); int line = 0; for(int i=1; i<=6;i++){ for(int j=1; j<=6;j++){ line++; // System.out.println(line + " : "+ i + " + " + j + " = " + (i+j)); int key = i+j; if ( cubeResult.containsKey(key)) { cubeResult.put(key, cubeResult.get(key) + 1); } else { cubeResult.put(key,1); } } } //only sort ArrayList myArrayList = new ArrayList(cubeResult.entrySet()); Collections.sort(myArrayList, new MyComparator()); DecimalFormat df = new DecimalFormat( "0.00" ); Double w = 0.0; //output sorted for( Object map : myArrayList ){ Map.Entry x = (Entry) map; w = 100.0/36.0 * x.getValue().doubleValue() ; System.out.println("Augenzahl: " + x.getKey() + "\tWürfelkombinationen: " + x.getValue() + "\tWahrscheinlichkeit: "+ df.format(w) + " %"); } } @SuppressWarnings("unchecked") static class MyComparator implements Comparator{ public int compare(Object obj1, Object obj2){ int result=0; Map.Entry e1 = (Map.Entry)obj1 ; Map.Entry e2 = (Map.Entry)obj2 ;//Sort based on values. Integer value1 = (Integer)e1.getValue(); Integer value2 = (Integer)e2.getValue(); if(value1.compareTo(value2)==0){ Integer word1=(Integer)e1.getKey(); Integer word2=(Integer)e2.getKey(); result=word1.compareTo(word2); } else{ //Sort values in a descending order result=value2.compareTo( value1 ); } return result; } } }