Schere, Stein, Papier in Java, was mache ich falsch?


21.05.2020, 23:05

Sorry für die Formatierung, die wurde erst nach dem abschicken der Frage so furchtbar.

3 Antworten

Wie wäre es mit einer Schleife?

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("Wie ist dein Name?");
    String name = s.nextLine();
    Random zufall = new Random();

    while (true) {
        System.out.println("Nimmst du 1=Stein, 2=Papier oder 3=Schere?");
        String wahl = s.nextLine();
        int wahl2 = Integer.parseInt(wahl);
        int zufallszahl = zufall.nextInt(2 + 1) + 1;
        System.out.print("Ich nehme ");
        System.out.println(zufallszahl == 1 ? "Stein" : zufallszahl == 2 ? "Papier" : "Schere");
        if (zufallszahl == wahl2)
            System.out.println("Unentschieden!");
        else {
            if (zufallszahl < wahl2 || zufallszahl == 3 && wahl2 == 1)
                System.out.println("Du hast gewonnen");
            else
                System.out.println("Du hast verloren");
            break;
        }
    }
}

PS: Auch deine originale Formatierung ist falsch ;)

Zu viele Leerzeichen und die Einrückungen sind auch falsch

codinghelp  21.05.2020, 23:36

Update: Gewinnerkennung hat nicht ganz funktioniert ^^

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("Wie ist dein Name?");
    String name = s.nextLine();
    Random zufall = new Random();

    while (true) {
        System.out.println("Nimmst du 1=Stein, 2=Papier oder 3=Schere?");
        String wahl = s.nextLine();
        int wahl2 = Integer.parseInt(wahl);
        int zufallszahl = zufall.nextInt(2 + 1) + 1;
        System.out.println("Ich nehme " +  (zufallszahl == 1 ? "Stein" : zufallszahl == 2 ? "Papier" : "Schere") + ", du nimmst " + (wahl2 == 1 ? "Stein" : wahl2 == 2 ? "Papier" : "Schere"));
        if (zufallszahl == wahl2)
            System.out.println("Unentschieden!");
        else {
            System.out.println("Du hast " + ((wahl2 - zufallszahl == 1 || zufallszahl == 3 && wahl2 == 1) ? "gewonnen" : "verloren"));
            break;
        }
    }
}
3

Bei Dir sind fast alle fehlenden Klammern am Programmende angehängt.

if(wahl2 == 1) {

Du musst die schließende Klammer } setzen, bevor Du

else if(wahl2 == 2) {

behandelst.

Sonst gehört dieses else zum unmittelbar davor stehenden "if (zufallszahl == 3) {".

Kannst du das ganze bitte bei hastebin.com oder hatebin.com hochladen? So tuh ich mir das nicht an.