If the below "if" stmt evalutes to TRUE then the value of Output = 20 or else 10..
Can someone explain how the increment operator works here.?
public class Test {
public static void main(String[] args) throws IOException {
int Output = 10;
boolean b1 = true;
if ((b1 == true ) && ((Output += 10) == 20)){
System.out.println("We are Equal = " + Output);
}
else{
System.out.println("Not Equal = " + Output);
}
}
}
It's not so much the += operator that is working differently; it's the && operator.
The && operator short circuits. If b1 is false, there's no way that b1 && (anything else) can be true, so it stops evaluating. As such, Output += 10 is not evaluated if b1 is not true, so Output will be 10.
If b1 is true, then it must continue to see if the remainder of the condition is true. In doing so, it must evaluate Output += 10, thereby increasing the value of Output by 10, making the value of Output 20.
The integer value 10 is added to the current value of Output. After this, the value of output is compared using the == operator, which only operates on booleans.
In this particular piece of code, since b1 is true and and Output is 20 after its value is increased by 10, the condition of the if block is true, therefore the else will be discarded and whatever code is inside the if block will be executed.
1) +=
means a "Pre-increment". So, with Output=10 the if block would proceed as below
if ((b1 == true ) && ((Output = Output + 10) == 20)){
here, value of Output will be compared with 20 once incrementation is done..So, during the first time
execution of the if block.. it would proceed as below..
if ((b1 == true ) && ((20) == 20)){
2)=+
means a "post-increment". So, value of Output will be compared with 20 before incrementation..So, during the first time execution of the if block.. it would proceed as below..
if ((b1 == true ) && ((10) == 20)){
hope this explaination helps :-)
Related
I'm coding a game in Netbeans using the GUI. In the game, a random amount of stones between 15-30 is generated and the user and the computer take turns removing stones between 1-3 until there are none left. The last player that takes the last stones loses. My problem is that my method (validIn()) won't be used in the playerMove(), so even when the conditions are met, the game doesn't update.
Here is where I think the problem is:
private boolean validIn(int num){
//
return num < 3 || num > 1 || num < totalStone;
}
public void playerMove(){
// Geting the user input
int userIn = Integer.parseInt(txtIn.getText());
// Declaring and assigning a boolean
boolean check = false;
// If the boolean returns true
if (check == true) {
// Subtracting how much the player took from the total amount of rocks
totalStone -= userIn;
// Displaying how many rocks were taken and how many are left
txtOut.setText(txtOut.getText() +"\nYou picked up " +userIn +" stone(s). There are " +totalStone +" stone(s) left.");
}
// Else,
else {
// Assign the boolean check to what the method validIn returns
check = validIn(userIn);
}
}
public void checkWinner(String player){
// If there are no more stones left,
if (totalStone == 0){
// Display a message that says who won
txtOut.setText(txtOut.getText() +"\nThere are no more stones left. "+player +" wins!");
}
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//
if (totalStone > 0){
// Display how many rocks there are
txtOut.setText(txtOut.getText() +"\nThere are " +totalStone +" stone(s).");
// The player does their move
playerMove();
// Checking if the computer won
checkWinner("The computer");
// Computer does a turn
computerMove();
// Checking if the player won
checkWinner("The player");
}
//
else if (totalStone == 0){
//
txtOut.setText(txtOut.getText() + "\nThe game has ended.");
}
}
int comIn = (int)(Math.random() * 2) + 1;
// Declaring and assigning a boolean
boolean check = false;
// If number generated is bigger than the total stones,
if (check == true && validIn(userIn) == true){...}
In above code you save the generated number in comIn but you never check comeIn is bigger than total stones in your code.
Then in if condition you are checking that is check equals to boolean true, which is not because you gave check a false value just above and never changed it so it will never run the if loop because inside it the first condition is wrong.
private boolean validIn(int num){
return num < 3 || num > 1 || num < totalStone;
}
Here it is returning true no matter what because the num provided is always less than 3 and greater than 1 if you are playing by your rules
`check = false;
// If the boolean returns true
if (check == true) {...} `
And here again you are setting the value of check false and checking that whether it is true in if loop, which will never run because check will never be true.
For you validIn method you need to think a little about the conditions you have for your method return statement.
The way it is written:
return true if num is ANY value less than 3 like 0, -50, 1, 2 but if it's not then
return true if num is ANY value greater than 1 like 2, 3, 1020, 323243 but if it's not then
return true if num is less than totalStones but if it's not then return false.
The condition to check if num is less than totalStones is never reached because you're using the OR (||) operator. With the use of the first and second conditions you will always be returned true. If the first condition (num < 3) is found to be true then true is instantly returned but if it's not then the second condition (num > 1) is checked and if it is found to be true then true is instantly returned. The third condition (num < totalStones) just can't be reached.
What you want to do is change the || operator to the AND (&&) operator:
return num < 3 && num > 1 && num < totalStone;
return true only if num is less than 3 and num is greater than 1 and num is less than totalStones.
By using the && operator you ensure that all three conditions must be met before true is returned. By saying this now, you can see that only a value of 2 in num will return a true. I think what you meant to use is:
return num <= 3 && num >= 1 && num < totalStone;
This way if num holds 1, 2, or 3 AND either of those values is less than totalStones then return true otherwise false is returned.
In your code, I see boolean Method always return true because you use
|| (OR)
any number less than 3 it will be returned true, or greater than 1 it will return true too.
and in your IF condition I didn't see you set variable check to true but you still have condition check is TRUE therefore that I wonder How can you use this variable to check your condition ?
So how can it jump inside if statement ?
The validIn(userIn) in the playerMove() method would never be reached for some reason. I have to remove the boolean check and change
if (check == true) to if ((validIn(userIn) == true)
So i Have this code going on, I need it to open a file, and scan the two integers in the file, then I need it to store the two numbers. The numbers are restricted to between 1 and 10 for the first number and between 1 and 39 for the second number. I have a valueCounter to make sure that the correct number gets stored in the correct variable. For some reason, the code always returns
"Your Initial Fib is out of range, eneter # between 1-10"
Which would be appropriate if the first number was greater than 10 or less than 1, but regardless of what i change the first number to, the code returns the same line. The only time it wont return that line is when i change the 2nd number to to be between 1 and 10. So I can conclude that the code is skipping the first number, but i cant figure out why. Any being of higher intelligence that can help?
private static File inFile = null;
private static PrintWriter outFile = null;
private static int startValue;
private static int lengthValue;
public static void main(String[] args) throws IOException
{
inFile = new File( inFileName);
Scanner in = new Scanner (inFile);
outFile = new PrintWriter (outFileName);
int valueCounter = 1;
while (in.hasNextInt())
{
int value = in.nextInt();
if ( value <= 39 && value >= 1 && valueCounter == 2)
{
lengthValue = value;
valueCounter ++;
}
if ( value > 39 || value < 1 && valueCounter == 2)
{
System.out.println("You are asking for too many Fib, eneter # between 1-39");
in.close();
System.exit(1);
}
if ( value <= 10 && value >= 1 && valueCounter == 1)
{
startValue = value;
valueCounter ++;
}
if ( value > 10 || value < 1 && valueCounter == 1)
{
System.out.println("Your Initial Fib is out of range, eneter # between 1-10");
in.close();
System.exit(1);
}
}
}
It is because of operator precedence, the && is evaluated before the ||. This makes the following expression
if ( value > 10 || value < 1 && valueCounter == 1)
evaluated to true the second round, because first value < 1 && valuecounter == 1 is evaluated, which is false. Next, value > 10 is evaluated, which is true. Or-ing both results in true, and the body executes. Use parentheses to control the order of evaluation.
if ( value > 10 || value < 1 && valueCounter == 1)
Seems to be always true and since its a normal outer "if" at the end of code, its always being called. overthink your "if" and its appearance
I'm trying to figure out how to check if three variables are all true or all false. So that the condition becomes true, when these variables have the same value and false, when they don't have the same value.
I thought something like (d == e == f) would help me here but the condition is only true when all variables are set to true. But when they're set to false, the condition doesn't work. Could anyone explain to me why? I know a very basic issue but I really can't figure it out myself.
You can try like this :
if((d && e && f) || (!d && !e && !f))
It will enter in loop either all will be true or all will be false.
It's because all expressions having relational operators return Boolean value.
So, first e == f is evaluated. As these both are false (both operators having same value) so, this expression return true value.
This true value is evaluated against d which is false. So that expression returns false (as both Operators have different values now) .
To know if the 3 variables are all true or all false; this what you can do:
boolean allTrue, allFalse;
if(a && b && c) allTrue = true; //a, b & c will evaluate to boolean and if all three vars are true the condition will be true and hence the if statement will be accessed
if(!a && !b && !c) allFalse = true; //if the not of the 3 is true, i.e (the 3 boolean vars are false), the whole condtion will be true and the if-statement will be accessed and the allFalse will be set to true means all 3 are false
boolean allTrue=false;
boolean allFalse=false;
boolean a,b,c;//your three variables
if(a && b && c)
{allTrue=true;}
else if(!a && !b && !c)
{allFalse=true;}
Try this, here i have two variable flags that are set to false initially, when one of the condition is true then only it woll be set to true so after the last line of code you can check if allFalse or allTrue has values true or false.
It should be possible to stay closer to the original formulation like this:
boolean eitherAllTrueOrAllFalse = (d == e) && (d == f)
If you only need to know if all are true or all false, then this will be more than enough:
boolean flagAllTrue = a && b && c;
No need to use a if else.
First think of the conditions separately:
boolean allTrue = a && b && c;
boolean allFalse = !(a||b||c);
Then combine them:
boolean eitherAllTrueOrAllFalse = allTrue|allFalse;
let sum = 0;
sum += a ? 1:0; sum += b ? 1:0; sum += c ? 1:0;
let allTrueOrAllFalse = ( sum === 0 || sum === 3 );
newbie here,
I have two variables which generate random numbers through .Random. I want them keep rolling until both variables generate two different values, simultaneously. Therefore, I'm using while loop with && for this purpose. As I have understood, please correct me if I'm wrong, the line while ((diceRolled1 != 5) && (diceRolled2 != 4)) translates as, keep rolling until the values of diceRolled1 is not equal to 5 AND diceRolled2is not equal to 4. But the program ends if either variable matches its value (diceRolled1 = 5 OR diceRolled2 = 4). This is not what && is supposed to do, right? I have ran the code like 10s of times, but not a single time it generated 5 and 4 at the same time.
I also tried ==on both sides and either side, but in that case the program didn't run at all, nor it gave any error.
Your help will be much appreciated. Thanks
import java.util.Random;
import static java.lang.System.out;
public class DiceRoller {
public static void main(String[] args) {
Random dice1 = new Random();
Random dice2 = new Random(); //Removing this doesn't work either
int diceRolled1 = 0;
int diceRolled2 = 0;
while ((diceRolled1 != 5) && (diceRolled2 != 4)) { //& didn't work either
diceRolled1 = dice1.nextInt(6) + 1;
diceRolled2 = dice2.nextInt(6) + 1;
out.println(diceRolled1 + " " + diceRolled2);
}
out.println("Program ends");
}
}
Your logic is incorrect. The loop will continue as long as both values don't match - as soon as one value matches, the loop exits. We can invert your logic to show this:
while (!(diceRolled1 == 5 || diceRolled2 == 4)) {
which is logically equivalent to what you have.
What you want is this:
while (diceRolled1 != 5 || diceRolled2 != 4) {
which says "Continue while any variable does not have the desired value"
You're getting the logical result you describe, but it wasn't what you expect. Specifically, when either of your conditions evaluates to false the logical and will not evaluate to true. I think you wanted
while (!(diceRolled1 == 5 && diceRolled2 == 4)) {
which is while not dice1 equal to 5 and dice2 equal to 4. And then, using De Morgan's Laws that might also be expressed as
while (diceRolled1 != 5 || diceRolled2 != 4) {
which means loop while dice1 is not equal to 5 or dice2 is not equal to 4.
the while execute the statement untill the condition is true.
In your code the condition is given by (diceRolled1 != 5) && (diceRolled2 != 4).
The && operator require true that all operands be true.
Given this Your loop will end when at least one of the expression will be false.
To finish the program when it generate 5 and 4 you have to use this:
(!(diceRolled1 == 5) && (diceRolled2 == 4))
Yeah,it should be. The program should end if dicerolled is either 5 or 4 because as far as it is not 4 and not 5 it is in while loop. It exits the while loop if only the value is either 4 or 5. So your logic is incorrect. Sorry! :)
Try:
while (!(dicerolled ==4 && dicerolled == 5))
In my program I have two dices with 100 faces. I make it count the amount of rolls it takes for dice one (d1) to equal 99 AND dice two (d2) to equal 26.
package diceroll;
import java.util.Random;
public class DiceRoll {
public static void main(String[] args) {
int count = 0;
int d1 = 0;
int d2 = 0;
while (d1 != 99 && d2 != 29) {
d1 = (int) (Math.random() * 100) + 1;
d2 = (int) (Math.random() * 100) + 1;
count += 1;
}
System.out.println(count + " " + d1 + " " + d2);
}
When using the AND operator (&&) the while loop only works until one of the numbers is found, however when using the OR operator (d1 != 99 || d2 != 29) the while loop works until both of them are matched.
Can somebody explain why OR gives the expected results, whilst AND doesn't?
The loop
while (condition)
keeps looping until condition is false. Your loop is:
while (d1 != 99 && d2 != 29) {
but both halves of the test must be true for the whole condition to be true. Once one of the numbers matches, one half will be false (it will not be not equal).
If you change the condition to OR:
while (d1 != 99 || d2 != 29) {
then only one side needs to be true for the whole condition to be true, or put another way, both sides need to be false for the whole condition to be false. This OR condition can be expressed in English as "while either of the numbers is not the target". Only when both numbers are their target is the entire condition false.
That's how AND works. It just looks for a single expression to return false to terminate the loop. It doesn't bother whether d1 is 69 or not, if d2 becomes 29 and vice versa.
But when you use OR, it checks for both the conditions. That way, even if d2 becomes 29 and d1 is still not 69 it continues to loop till d1 becomes 69, and thus evaluating to false only when both the conditions are satisfied.
When you're using &&, if one of the dice doesn't equal the desired number, your conditional still returns false. For example, if d1=99 and d2=1, your while conditional would read: 99 != 99 && 1 != 29 -> false && true -> false. So it exits.
Yeah, I understand it now. By using while not and OR logic, I created NOR logic which has the following table:
A B Z
0 0 1
0 1 0
1 0 0
1 1 0
Thanks for the help guys! :)