Java :: Aufgabe #6 :: Lösung #11

10 Lösungen Lösungen öffentlich
#6

Würfelspiel (mit Random)

Anfänger - Java von Jurom - 22.10.2012 um 10:45 Uhr
Das Programm soll ein einfaches Glücksspiel simulieren.
Lassen Sie 2 Zufallszahlen zwischen 1-6 ausgeben, die höhere Zahl gewinnt.
Wiederholen sie das Würfeln solange, bis der Anwender gewinnt.
#11
vote_ok
von TheChuggler (120 Punkte) - 29.06.2021 um 12:24 Uhr
Quellcode ausblenden Java-Code
/** Short dice game against the computer. You win when your number is greater! */

import java.util.Random;

class DiceGame {
    public static void wait(int ms) {
        try {
            Thread.sleep(ms);
        } catch (Exception ex) {
            System.out.println("Error during waiting time!");
        }
    }
    
    public static void main(String[] args) {
        boolean win = false;
        int counter = 0;
        Random random = new Random();
        System.out.println("Lets\'s play a dice game!");
        wait(1000);
        System.out.println("You win when your number is greater than mine!");
        wait(1000);
        while (!win) {
            int myNumber = random.nextInt(6) + 1;
            int yourNumber = random.nextInt(6) + 1;
            System.out.println("Your number is: " + yourNumber);
            wait(1000);
            System.out.println("My number is: " + myNumber);
            wait(1000);
            if (yourNumber > myNumber) {
                System.out.println("You won!");
                wait(1000);
                if (counter == 1) {
                    System.out.println("I won " + counter + " round, before you won 1 round!");
                } else {
                    System.out.println("I won " + counter + " rounds, before you won 1 round!");
                }
                win = true;
            } else {
                counter++;
                System.out.println("I won!");
                wait(1000);
                System.out.println("Let\'s play another round!");
                System.out.println("");
                wait(1000);
            }
        }
    }
}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben