Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a conditional statement

I am a student learning Java and am stuck on the last part of a homework problem. I need to write a conditional statement that prints whether the roll of the dice was a Yahtzee or not (all five dice are equal to one another). I cannot figure out how to do this since I used ints and not boolean. I know I cannot cast an int into boolean and up to this point this casting is the only way I know how to change variables. Any help would be appreciated since the ways to achieve what I am looking for have been more than I can understand at this point. This is what I have and the issue is in the second to last line.

import java.util.Random;

public class FiveDice_JLR
{
   //-----------------------------------------------------------------
   //  Generates random numbers in various ranges.
   //-----------------------------------------------------------------
   public static void main(String[] args)
   {
      Random generator = new Random();
      int die1, die2, die3, die4, die5;

      die1 = generator.nextInt(6)+1;
      System.out.println("Die 1: " + die1);

      die2 = generator.nextInt(6)+1;
      System.out.println("Die 2: " + die2);

      die3 = generator.nextInt(6)+1;
      System.out.println("Die 3: " + die3);

      die4 = generator.nextInt(6)+1;
      System.out.println("Die 4: " + die4);

      die5 = generator.nextInt(6)+1;
      System.out.println("Die 5: " + die5);


      **if(die1==die2&==die3==die4&==die5&&);**
      {
      System.out.println("Yahtzee!!!!");
      }

   }
like image 653
JenRut Avatar asked Dec 03 '25 17:12

JenRut


1 Answers

If you use just &, that is the bitwise AND, therefore it compares the bits of all the numbers. What you want is &&, which is logical AND:

if(die1 == die2 && die2 == die3 && die3 == die4 && die4 == die5) {
    // Something here...
}

Also note that each && operator just like the == operator, requires 2 operands to properly compare


Assuming all your values are positive, another method to check if all numbers are equal to each other is to add them all up and check if the sum is equal to 5 times one of the values.

if((die1 + die2 + die3 + die4 + die5) == die1 * 5) {
    // Something here...
}

This is doing the same thing and is shorter, but is prone to error because you may in the future decide to generate negative numbers (for some reason), or decide to use more dice and forget to change 5 to the appropriate number, etc. In general, just stick to the first one

like image 147
smac89 Avatar answered Dec 06 '25 10:12

smac89



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!