lotto/src/gfn/marc/Lottozahlen.java

81 lines
2.6 KiB
Java

package gfn.marc;
import java.util.*;
public class Lottozahlen {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean eingabeKorrekt = false;
// Lottoschein ausfüllen
HashSet<Integer> lottoschein = new HashSet<>(6);
while (!eingabeKorrekt) {
System.out.println("Bitte geben Sie sechs, mit Kommata getrennte, Lottozahlen (1 - 49) ein. " +
"(Beispiel: \"6,12,29,34,40,46\")");
String eingabe = scanner.next();
if (eingabe.matches("([1-4][0-9][,]|[0-9][,]){5}[1-4][0-9]|[0-9]")) {
String[] zahlen = eingabe.split("[,]");
for (String zahl : zahlen) {
lottoschein.add(Integer.parseInt(zahl));
}
// Prüfung: Doppelte Zahlen?
if (lottoschein.size() == 6) {
eingabeKorrekt = true;
} else {
System.err.println("Doppelte Zahlen!");
}
} else {
System.err.println("Ungültige Zahlen!");
}
}
// Lottozahlen ziehen
HashSet<Integer> lottozahlenSet = new HashSet<>(6);
for (; lottozahlenSet.size() < 6;) {
lottozahlenSet.add((int) (Math.random() * 49) + 1);
}
ArrayList<Integer> lottozahlen = new ArrayList<>(lottozahlenSet);
// Lottozahlen ausgeben
System.out.println();
System.out.print("Lottozahlen: ");
Collections.sort(lottozahlen);
for (int i = 0; i < lottozahlen.size(); i++) {
if (i < lottozahlen.size() - 1) {
System.out.print(lottozahlen.get(i) + ", ");
} else {
System.out.print(lottozahlen.get(i));
}
}
System.out.println("\n");
// Lottoschein auswerten
ArrayList<Integer> richtige = new ArrayList<>();
for (int zahl : lottoschein) {
if (lottozahlen.contains(zahl)) {
richtige.add(zahl);
}
}
// Ergebnis ausgeben
Collections.sort(richtige);
System.out.println(richtige.isEmpty() ? "Sie haben leider keine richtige Zahl!" :
"Sie haben " + richtige.size() + " Richtige: ");
if (!richtige.isEmpty()) {
for (int i = 0; i < richtige.size(); i++) {
if (i < richtige.size() - 1) {
System.out.print(richtige.get(i) + ", ");
} else {
System.out.print(richtige.get(i));
}
}
}
}
}