ARadauer
Top Contributor
ach ja.. zum lernen für eine mögliche Nachklausur...
Java:
import java.util.Random;
public class Wuerfeln {
static Random rnd = new Random();
public static void main(String[] args) {
int[] zahlen = new int[6]; // das feld für die zahlen
int pos = 0; // aktuelle position im feld
int anzahlWuerfe = 0; // wie oft haben wir gewürfelt
while (pos < 6) { // solande wir noch nicht voll sind
int wurf = wuerfle(); // würfeln
anzahlWuerfe++; // anzahl der würfe erhöhen
if (!contains(wurf, zahlen)) { // wenn die zahl nicht drinnen ist
zahlen[pos] = wurf; // an aktuelle positon setzen
pos++; // weiterrücken
}
}
System.out.println("Die Zahlen: ");
printArray(zahlen);
System.out.println("sortiert: ");
sort(zahlen);
printArray(zahlen);
System.out.println("Würfe: " + anzahlWuerfe);
}
public static int wuerfle() {
return rnd.nextInt(6) + 1;
}
public static boolean contains(int zahl, int[] array) {
for (int i = 0; i < array.length; i++) { // übers feld iterieren
if (array[i] == zahl) // ist die akutelle die gesuchte
return true; // ja sie ist enthalten
}
return false; // wir sind am ende, nich drinnen
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.println();
}
// google erster treffer zu insert sort
public static void sort(int[] array) {
int i, j, t;
for (i = 1; i < array.length; i++) {
j = i;
t = array[j];
while (j > 0 && array[j - 1] > t) {
array[j] = array[j - 1];
j--;
}
array[j] = t;
}
}
}