Проблема с ведением счета с помощью цикла while (Java) - PullRequest
0 голосов
/ 07 марта 2019

Я нахожусь во введении в класс java, и для одного из моих заданий я должен использовать цикл (для или во время), чтобы отслеживать результаты между мной и компьютером.

Вотточное слово в слово инструкции от моего профессора:

Напишите программу, которая делает это: Вы (как программист) являетесь дилером.выберите случайное число для себя (от 0 до 100).Попросите пользователя ввести случайное число (от 0 до 100). Кто ближе к 21, выигрывает игру.

(часть 2) - цикл (ведение счетчика), запустите одну и ту же программу и продолжайте ее так, чтобы она продолжала играть (разыгрывать руки и говорить, кто победит), пока пользователь не введет 21, после чего вы распечатываете некоторыеСтатистика и сказать до свидания.Например, ваше прощание может выглядеть так:

Количество сыгранных раундов: 5 Дилер выиграл: 3 Игрок выиграл: 2

вы 2 на 5.

СейчасЯ написал код и играл с ним часами и часами, и не могу заставить его работать с циклом.Я пробовал время, делать время и для.Я искал повсюду в Интернете подобные примеры, но не могу заставить цикл работать в моей программе.Если у кого-то есть какие-либо предложения, я буду благодарен за отзыв.

мой код:

    import java.util.*;

class asd {


    public static void main(String[] args) {


        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome Valued player, take your guess!");


        int min = 0;
        int max = 100;
        int input;
        int c = 21;
        int count = 0;
        int userscore = 0;
        int dealerscore = 0;
        int gamesplayed = 0;


        Random rand = new Random();


        int r = rand.nextInt(max - min) + min;
        input = sc.nextInt();
        System.out.println("computer's number:" + r);


        if (Math.abs(input - c) <= Math.abs(r - c)) {
            System.out.println("the winner is the user!" + input);
            dealerscore++;
            gamesplayed++;


        } else {
            System.out.println("the winner is the computer!" + r);
            userscore++;
            gamesplayed++;
        }
        if (input == c) {
            System.out.println("thank you for playing. you won.");

        }

        if (r == c) {
            System.out.println("Thank you for playing:" + userscore);
            System.out.println(userscore);


        }

        if (input == 0) {
            System.out.println("Number of hands played:" + gamesplayed);
            System.out.println("Dealer won:" + dealerscore);
            System.out.println("User won:" + userscore);
        }

        while (input != c && r != c)
            gamesplayed++;


    }


    // TODO code application logic here
}

Все работает нормально, но я не могу заставить цикл работать где-либо здесь.

Ответы [ 3 ]

1 голос
/ 07 марта 2019

Вам нужен цикл while, содержащий вашу игровую логику. Условие должно просто проверить, если input != c.

Затем внутри цикла продолжайте спрашивать пользователя о вводе. Кроме того, вы смешали userscore и dealerscore при добавлении счета.

Затем в конце, как только вы выйдете из цикла, вы можете распечатать результаты / статистику.

Пожалуйста, прочитайте комментарии ниже:

import java.util.*;

public class MyClass {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome Valued player, take your guess!: ");

        int min = 0;
        int max = 100;
        int input;
        int c = 21;
        int count = 0;
        int userscore = 0;
        int dealerscore = 0;
        int gamesplayed = 0;

        Random rand = new Random();
        int r = rand.nextInt(max - min) + min;
        input = sc.nextInt();

        /*
        This loop runs the game until the user enters 21
        */
        while (input != c) {
            System.out.println("Computer's number:" + r);

            if (Math.abs(input - c) <= Math.abs(r - c)) {
                System.out.println("The winner is the user! " + input);
                userscore++; //You mixed up userscore and dealerscore
            } else {
                System.out.println("The winner is the computer! " + r);
                dealerscore++; //You mixed up userscore and dealerscore
            }

            /*
            User needs to keep entering guesses
            */
            System.out.println();
            System.out.println("Enter another guess: ");
            r = rand.nextInt(max - min) + min;
            input = sc.nextInt();
        }

        /*
        You don't need any conditions since the games have already ended
        But it should be outside and after the loop
        */
        System.out.println("Number of hands played:" + gamesplayed);
        System.out.println("Dealer won:" + dealerscore);
        System.out.println("User won:" + userscore);
    }
}

0 голосов
/ 07 марта 2019

Попробуй это.Просто обратитесь к коду для объяснений.

import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome Valued player, take your guess!");
        System.out.println("");

        int min = 0;
        int max = 100;
        int input;
        int c = 21;
        int userscore = 0;
        int dealerscore = 0;
        int gamesplayed = 1;

        Random rand = new Random();

        while (true) { // so that the game will keep playing
            System.out.println("----------------- ROUND " + gamesplayed + " -----------------");
            int r = rand.nextInt(max - min) + min; // computer's choice

            while (true) { // so that it will keep asking the user in case the user enters an invalid input
                try {
                    System.out.print("Enter a random number! :");
                    input = Integer.parseInt(sc.nextLine());
                    break;
                } catch (Exception e) {
                    System.out.println("Invalid input!");
                }
            }

            System.out.println("The computer's random number is " + r);

            // checking for the rounds winner
            if (Math.abs(input - c) <= Math.abs(r - c)) {
                System.out.println("The winner is the user!");
                userscore++;
            } else {
                System.out.println("The winner is the computer!");
                dealerscore++;
            }

            if (input == c) { // checking for ending the game
                System.out.println("================ GAME STATS ================");
                System.out.println("Thank you for playing.");
                System.out.println("Number of hands played: " + gamesplayed);
                System.out.println("Dealer score: " + dealerscore);
                System.out.println("User score: " + userscore);
                System.out.println("You are " + userscore + " out of " + gamesplayed + "!");
                System.out.println("============================================");
                sc.close();
                break;
            }

            gamesplayed++; // increment games played

            System.out.println("--------------------------------------------");
        }

    }

}
0 голосов
/ 07 марта 2019

Изменить цикл с помощью

      while (input != c && r != c){
          gamesplayed++;
          System.out.println("Games played: " + gamesplayed );
      }

вы увидите, что это работает. Я бы лучше отформатировал код, чтобы легче было его отлаживать, и всегда использовал бы скобки.

...