Problem 2: I wrote a program to roll a pair of die and count the number of rolls. The program would end if it gets a 1,1.
public class NewEmptyJavaApp2 {
public static void main(String args[])
{
int x=0;
int y=0;
int count = 0;
int count1 = 0;
int count2 = 0;
while(true)
{
x=(int)(6*Math.random()+1);
y=(int)(6*Math.random()+1);
count++;
if(x!=1 && y!=1) //Here lies the problem.if changed to || works well
{ count1++;
System.out.println("'"+x+"','"+y+"'");
}
else
{
count2++;
System.out.println("'"+x+"','"+y+"'");
break;
}
}
System.out.println("Total:"+count);
System.out.println("Non snake:"+count1);
System.out.println("snake:"+count2);
}
}
The problem here is the && operator. From my understanding && is supposed to evaluate both conditions but in this case if x=1 and y>2 the program would end which is totally incorrect.
Please could someone help me clarify these issues. Thanks.
Your understanding of the && operator is not correct. The && operator evaluates to true only (and thats a big ONLY) if all conditions specified evaluates to true.
so in your case, the first part evaluates to false (i.e. x != 1) and the second part will return true, as y != 1 will be true for all values of y excepting 1. Thus causing your if block to be evaluated.
There are two solutions. One is simply switching your test so that instead of what you have up there, you do the following.
if(x==1 && y==1) //Here lies the solution
{
count2++;
System.out.println("'"+x+"','"+y+"'");
break;
}
else
{
count1++;
System.out.println("'"+x+"','"+y+"'");
}
So in effect, you're testing for when both dice return 1(i.e. equals 1) and if nthey do, you quit, else you continue.
The Second and PREFERED solution is to re-write the entire program properly as it is quite crappy the way it is now.
Too many counters, bad variable names, etc.
Here's a solution I came up with,
public class RollCounter
{
private int firstDice = 0;
private int secondDice = 0;
private int numRolls = 0;
private void rollDice()
{
firstDice = (int) (6* Math.random() + 1);
secondDice = (int) (6* Math.random() + 1);
numRolls++;
}
public void run()
{
while(true)
{
rollDice();
if (firstDice == 1 && secondDice == 1)
break;
else
{
System.out.println("Dice 1: " + firstDice + ", Dice 2: " + secondDice);
}
}
System.out.println("Total Rolls: " + numRolls );
}
/**
* @param args
*/
public static void main(String[] args)
{
RollCounter counter = new RollCounter();
counter.run();
System.out.println("Game Ended!");
}
}
As seen, the names represent the program more effectively, only 1 counter used etc etc,
As for question 1, I am at a loss as to what the problem is???