0

I'm working on building out a sample dice rolling game that rolls the dice 10 times unless interrupted by user input.

I have a while statement that runs based on the state of two boolean values, one of which is set based on the user input.

My current progress is below. Any suggestions would be a huge help!

import java.util.Scanner;
import java.swing.JOptionPane;
import java.util.Random;


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


     Random rand = new Random();


      int player1Wins = 0;
      int player2Wins = 0;
      int ties = 0;
      int rollCount = 0;
      boolean rollAgain = true;

      while (rollCount < 10 && rollAgain)
      {
         int player1Dice = rand.nextInt(6) + 1;
         int player2Dice = rand.nextInt(6) + 1;

         if (player1Dice > player2Dice)
         {
            player1Wins++;
            System.out.println("Player 1 wins!!");
         } 

         else if (player2Dice > player1Dice)
         {
            player2Wins++;
            System.out.println("Player 2 wins!!");
         }

         else 
         {
            ties++;
            System.out.println("It's a tie...");
         }

         rollCount++;
         String answer;
         Scanner keyboard = new Scanner(System.in);
         System.out.println("Would you like to roll again? Press y for yes");
         answer = keyboard.nextLine();

         if (answer == "y") 
         {
            rollAgain = true;
         }

         else
         {
            rollAgain = false;
         }

      }
      System.out.println();
      System.out.println("Player 1 Total wins: " + player1Wins);
      System.out.println("Player 2 Total wins: " + player2Wins);
      System.out.println("Total Ties: " + ties);
      System.out.close();
   }
}
Josh
  • 1,165
  • 3
  • 24
  • 44
  • 3
    Regarding, `if (answer == "y")`, don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead do, `if (answer.equals("y"))` – Hovercraft Full Of Eels Oct 20 '19 at 19:53
  • Probable duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Hovercraft Full Of Eels Oct 20 '19 at 19:54
  • Side issue: only create *one* Scanner object based on `System.in`. You're creating multiple such instances within your while loop, so create your Scanner object *before* the loop. – Hovercraft Full Of Eels Oct 20 '19 at 19:57
  • 1
    Got it so place 'keyboard' outside of the while loop? Also would I use ```if(answer.equals("y"))``` to evaluate that user input? – Josh Oct 20 '19 at 20:00
  • What happens when you try this? – Hovercraft Full Of Eels Oct 20 '19 at 20:00
  • Currently I get 4 errors: ```DiceGame.java:21: error: variable rollAgain is already defined in method main(String[]) boolean rollAgain = true; ^ DiceGame.java:23: error: bad operand types for binary operator '&&' while (rollCount < 10 && rollAgain) ^ first type: boolean second type: String DiceGame.java:56: error: incompatible types: boolean cannot be converted to String rollAgain = true; ^``` – Josh Oct 20 '19 at 20:04
  • Then fix those errors: don't re-declare rollAgain, for one – Hovercraft Full Of Eels Oct 20 '19 at 20:05
  • Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – J. Murray Oct 21 '19 at 00:25

1 Answers1

1

Try to break down the code based on the single responsability principle. Clean code, easy to test, and much mmore granular.

I did one quick implementation, far to be the best solution, but it is just to exemplify tsuch principle:

Dice object, but could be named as Player I think

public class Dice implements Comparable<Dice> {

    private int number;

    public Dice(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }

    @Override
    public int compareTo(Dice o) {
        return Integer.compare(number, o.number);
    }
}

Counter - check the rolls, show the winner and keep results

public class Counter {

    private int playerOneWins;
    private int playerTwoWins;
    private int ties;

    public void check(Dice player1, Dice player2) {

        if (player1.compareTo(player2) > 0) {
            System.out.println("Player 1 wins!!");
            playerOneWins++;
        } else if (player2.compareTo(player1) > 0) {
            System.out.println("Player 2 wins!!");
            playerTwoWins++;
        } else {
            System.out.println("It's a tie...");
            ties++;
        }
    }

    public void showResults() {
        System.out.println();
        System.out.println("Player 1 Total wins: " + playerOneWins);
        System.out.println("Player 2 Total wins: " + playerTwoWins);
        System.out.println("Total Ties: " + ties);
        System.out.close();
    }
}

Input Reader - know how to get inputs from user

public class InputReader {

    private static final String YES = "y";

    private Scanner keyboard = new Scanner(System.in);

    public boolean askUser() {

        System.out.println("Would you like to roll again? Press y for yes");

        String answer = keyboard.nextLine();

        return YES.equalsIgnoreCase(answer);
    }
}

Roller - create number / throw the dices

public class Roller {

    private Random random = new Random();

    public Dice roll()
    {
        return new Dice(random.nextInt(6) + 1);
    }
}

And, finnaly, this is the main class:

public class Game {

    private static final int MAX_ROLLS = 10;

    private Roller roller = new Roller();
    private Counter counter = new Counter();
    private InputReader inputReader = new InputReader();

    public void start() {

        int rolls = 0;
        boolean continueRolling = true;

        while (rolls <= MAX_ROLLS && continueRolling) {

            Dice player1 = roller.roll();
            Dice player2 = roller.roll();

            counter.check(player1, player2);

            rolls++;

            continueRolling = inputReader.askUser();
        }

        counter.showResults();
    }

    public static void main(String[] args) {
        new Game().start();
    }
}

I hope it helps you to understand such principle.

Community
  • 1
  • 1
  • I was going to say: "No Comment" but on the other hand if the game code was to get to this point wouldn't it be a good idea to show what is going on during the game such as: Game introduction and 'Hit ENTER to start game'. Player 1 could be the computer which indicates its dice roll then, Player 2 (User) is asked to Hit ENTER to roll the dice and that roll value is displayed. The Winner or Tie of that roll segment is immediately displayed. You know...show the scenario. Just a thought. – DevilsHnd - 退職した Oct 20 '19 at 21:07
  • @DevilsHnd - it would be nice, but changing behavior of his code was not what I wanted to do. My idea was just to show him how to sort of "clean code" a bit his own idea. – VeryNiceArgumentException Oct 21 '19 at 14:02