Java n00b here. I am putting together a little random number game and am having trouble with my loss condition test. It seems like Java does not like casting ints as a bools.

Here is my code so far:

import java.util.*;

public class TwoRandom
{
	public static void main (String[] args)
	{
		System.out.println ("\n This program will generate two random integers between 1 and 7.");
		System.out.println ("You win if the difference between the numbers is even.");
		System.out.println ("You lose if the difference between the numbers is odd.");
		System.out.println ("If the numbers are the same a tie is declared.");

		int num1 = (int) (Math.random() * 7 + 1);
		int num2 = (int) (Math.random() * 7 + 1);

		if (num1 == num2)
		{
			System.out.println ("\n A TIE!  =/ " + num1 + " " + num2);
		}
		// If num1 and num2 are even the difference will be even
		// If num1 and num2 are odd the difference will be even
		// Ergo the lose condition is rolling one even number and one odd number
		if ((num1 % 2 || num2 % 2) && (num1 % 2 != num2 % 2))
		{
			System.out.println ("\n YOU LOSE! ='( " + num1 + " " + num2);
		}
		else
			System.out.println ("\n YOU WIN! =D " + num1 + " " + num2);
	}
}

for line 22 I tried casting the ints as bools and the compiler screamed at me. Should I declare new bool variables before doing the test? If so how would you suggest I go about converting the ints to bools via new variables?

Thank you for any help!
-Optikali

In Java a booolean is a boolean, and an int is an int. 0 is not false, and 1 is not true. You can change your code to something like:

if (((num1 % 2 == 1) || (num2 % 2==1)) && (num1 % 2 != num2 % 2))
{
   System.out.println ("\n YOU LOSE! ='( " + num1 + " " + num2);
}

And this should work :)

One more comment - you are using Math.random() in order to create integers. It will be much easier to use the java.util.Random class, and using its nextInt(int n) method.

commented: Correct, concise, and illuminating! +2

Oh wow, don;t know why being more explicit didn't occur to me! Thanks so much for not only an answer, but meaningful suggestions and explanations!

You rock!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.