While loop seems to ignore "or" operator - java

I'm having trouble figuring out what's wrong with my code for a "rock paper scissors" game for my Comp Sci class. The part I'm having trouble with is this:
while((userscore < 4) || (compscore < 4)){
if(userhand.equalsIgnoreCase("R") && comphandint == 0){
JOptionPane.showMessageDialog(null, "Rock vs. Rock: \nYou Tie");
}
else if(userhand.equalsIgnoreCase("R") && comphandint == 1){
compscore += 1;
JOptionPane.showMessageDialog(null, "Rock vs. Paper: \nYou Loose");
...
}
The loop works except for the fact that it loops until both userscore and compscore are equal to 4. I want it to loop until only one of the two hits 4. Any ideas?

You should use && (and) rather than || (or).
A simple logic table shows us the result of both;
| AND | OR
value1 | true | true
value2 | false | false
result | false | true
(This is for the benefit of others finding this question later)
So as you can see, with OR if either of the values are below 4 then true will be returned and the loop will be entered. With AND, as long as one of the values is 4 or above false will be returned and the loop will stop - as you wanted.
Hope this helps you, and anyone else who finds this question in future.

Related

If else condition combine && and || in one row statement

Thank you for your time, i create some if else statement in checkbox to display result, can i combine && and || condition in one statement? for example
if (radioMale && chestPain && (leftArm || bothArm || jaw || throat)) {
highPossibilityOfHeartDisease = true;
}
User have to tick radioMale && chest pain && can tick either leftArm, bothArm, jaw or throat (one or more) to return true for highPossibilityOfHeartDisease. Is the code above valid? need some help here.
Yes you can combine && and || in a if...else statement. See it logically before considering programmatic side.
true AND true AND true AND (true OR false OR false) the condition inside brackets will be verified and set as one resulted Boolean that may be true or false according to the condition.
Then the resulting booleans will be verified linearly as normal.
You can read some articles explaining maths of boolean expressions, for example:
The Mathematics of Boolean Algebra: From StanFord University
Boolean Expressions
Boolean algebra

can you have two conditions in an if statement

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}

JAVA Intellij Coding

String marital = (String) JOptionPane.showInputDialog("Are you a single or married joint filer?");
while ((marital.length() >= 6) && (marital.length() <= 7)) {
System.out.println("You are " + marital + " thank you.");
if (marital.length() > 7) {
break;
}
}
im pretty new to Java so i was wondering how i could stop the while loop from printing more than one line. The objective is that the user will say single or married but i dont know how to only print it once
Just put break; after print, just like that, no if or anything. Right now you have your break inside if, that checks condition that will for sure fail, because if there was a possiblity that marital.length > 7 then it wouldn't even enter this while loop, since you are making sure that it's length is 7 or lower. All this code is weird tho, you are probably doing all this to train/learn, but I suggest just doing this:
String marital = (String) JOptionPane.showInputDialog("Are you a single or married joint filer?");
if ((marital.length() == 6) || (marital.length() == 7)) {
System.ou.tprintln("You are " + marital + " thank you.");
}
That will check if martital length is 6 OR 7 (you had something like that in your code, expressed in a convoluted way) and if yes then it's gonna print your sentence.

(Code Review) Java if statement involving logical and(&&) operator [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have started programming a few weeks ago in java/android. I want to write a small tic tac toe game as an android app but I'm having trouble with my method that will check for the winner. It is as follows:
public void checkForWinner() {
if( taken[0] && taken[3] && taken[6] ||
taken[0] && taken[1] && taken[2] ||
taken[2] && taken[5] && taken[8] ||
taken[6] && taken[7] && taken[8] ||
taken[0] && taken[4] && taken[8] ||
taken[2] && taken[4] && taken[6] ||
taken[1] && taken[4] && taken[7] ||
taken[3] && taken[4] && taken[5] == 1 ){}
}
Here I have an array called taken that holds 9 integers, each of those integers being either a one, meaning player one owns that block, or a two, meaning player two ows that block. Current, I am trying trying all possible scenarios in which player one would be the winner but eclipse is telling me that The operator && is undefined for the argument type(s) int, int. The error only seems to be showing for the first logical and operation of each line of the if statement. For example the first error goes up to taken[0] && taken[3] and then disappears until the next line.
Alternatively, you can check taken[n] values to see if they hold 1 or 2, if you think that'd make your code clearer:
(taken[0]==1 && taken[3]==1 && taken[6]==1)
Keep in mind that the && operator expects boolean operands...so it won't work with your int array the way you're expecting it to.
Swap your && to ==, you're trying to see if they're all the same value I assume which would show a winner, and be sure to use parentheses to sort it out, so one win condition would look like
((taken[0] == taken[3]) && (taken[0] == taken[6]))
However, this will only tell you that some player won, not which player. I guess you could check to see which player made the last move once it is determined that some one has won and declare that player as the winner.
In java,
if (a && b) or if (a || b)
works only if a and b are booleans / boolean expressions.
Here I have an array called taken that holds 9 integers, each of those integers being either a one, meaning player one owns that block, or a two, meaning player two owns that block.
In that case, you can replace the logical operators with bitwise operators:
int winner = taken[0] & taken[3] & taken[6]
| taken[0] & taken[1] & taken[2]
| taken[2] & taken[5] & taken[8]
| taken[6] & taken[7] & taken[8]
| taken[0] & taken[4] & taken[8]
| taken[2] & taken[4] & taken[6]
| taken[1] & taken[4] & taken[7]
| taken[3] & taken[4] & taken[5];
Then the variable winner will contain 1 if player 1 won, 2 if player 2 won, 0 if neither of them won, or 3 of both of them won (which probably isn't possible in your game).
1) You cant use && or || operators on int variables because the are meant for boolean values.
2) also use brackets to group conditions like
if (
(taken[0]==1 && taken[3]==1 && taken[6]==1)||
(taken[0]==1 && taken[1]==1 && taken[2]==1)||
...
OK there are two main problems here.
First, taken[0] needs to return either true or false to be able to remain as-is within the if-statement. You have mentioned it is an integer, so for it to return true or false, you'll need to do a comparison, such as taken[0] == 1.
Second, you need to use parentheses and do some groupings. Java does not respect whitespace. Instead of if( taken[0] && taken[3] && taken[6] || ..., you'll need to do if( (taken[0] && taken[3] && taken[6]) || .... That is, you need to put parentheses around each set of groupings.
The reason Eclipse is erroring is because the && operator is only for comparing booleans. That is true && true. You're giving it integers and it doesn't like that.
One way you might want to solve this is to write a function that determines if a solution is reached. So maybe something like:
private boolean isSolutionPresent(int[] taken, int index1, int index2, int index3) {
return (taken[index1] == 1 ) && (taken[index2] == 1) && (taken[index3] == 1);
}
Then you could convert your if statement to something like:
if (isSolutionPresent(taken, 0, 3, 6) ||
isSolutionPresent(taken, 0, 1, 2) ||
isSolutionPresent(taken, 2, 5, 8) || //... etc, removing the final ==1
Since the isSolutionPresent method returns a boolean (that is, true/false) you can apply the || operator to it.

Scalable solution for Rock-Paper-Scissor

Just went through a variant of the game : Rock-Paper-Scissor-Lizard-Spock
I have written a Java code for traditional R-P-S problem, but when I tried extending my code for the newer version of the game (R-P-S-L-S)..I felt my code is terribly bad. Here is a snippet :
if (player1.equals("ROCK") &&
player2.equals("SCISSORS")) {
winner = 1;
}
// Paper covers rock...
else if (player1.equals("PAPER") &&
player2.equals("ROCK")) {
winner = 1;
}
// Scissors cut paper...
else if (player1.equals("SCISSORS") &&
player2.equals("PAPER")) {
winner = 1;
}
else {
winner = 2;
}
I realized the code cant be extended easily for the newer version - as well as for more than 2 players. This is mainly because of multiple if/else or switch/cases. I need some help re-designing my code for achieving the 2 objectives :
Further modification as per R-P-C-L-S problem.
Support for more than 2 players.
I don't need code, just some guidelines should help.
Thanks !!
EDIT : Seems like I was wrong in thinking that this game can be played by more than 2 players. I am sorry for this mistake, please ignore the second requirement.
In, Rock-Paper-Scissor games, it is easy to decide if move a wins against move b using their index at a cycle. So you don't have to manually decide in your code the result of every combination as other answers here suggest.
For the Rock-Paper-Scissor-Spock-Lizard version:
Let's assign a number to each move (0, 1, 2, 3, 4).
Notice that every move beats two moves:
The move previous to it in the cycle (or four cases ahead)
The move two cases ahead in the cycle
So let d = (5 + a - b) % 5. Then:
d = 1 or d = 3 => a wins
d = 2 or d = 4 => b wins
d = 0 => tie
For the Rock-Paper-Scissor version:
let d = (3 + a - b) % 3. Then:
d = 1 => a wins
d = 2 => b wins
d = 0 => tie
Generalization For n >= 3 and n odd:
Let d = (n + a - b) % n. Then:
If d = 0 => tie
If d % 2 = 1 => a wins
If d % 2 = 0 => b wins
The nature of Rock-Paper-Scissors is such that you have to explicitly handle the case for every possible combination of states. So the number of cases you have to cover increases exponentially with the number of players, and polynomially (with the order of the polynomial being the number of players) with the number of options.
Having said that, Java's enums are good for this kind of thing.
Here's my stab at it:
import java.util.Arrays;
import java.util.List;
enum Result {
WIN, LOSE, DRAW;
}
enum Option {
ROCK(SCISSORS),
PAPER(ROCK),
SCISSORS(PAPER);
private List<Option> beats;
private Option(Option... beats) {
this.beats = Arrays.asList(beats);
}
Result play(Option other) {
if beats.contains(other) {
return Result.WIN;
} else if other.beats.contains(this) {
return Result.LOSE;
} else {
return Result.DRAW;
}
}
}
Adding more cases (Lizard and Spock) is consequently relatively simple. Adding more players would be more complicated; among other things, you'd have to determine what the rules of three-player Rock-Paper-Scissors even are, because I have no idea.
i think: 1 beats 2 or 5 loses to the rest. 2 beats 3 or 1 loses to the rest. 3 beats 4 or 2 loses to rest. 4 beats 5 or 3 loses to the rest. 5 beast 1 or 3 loses to the rest. For 3 players, compare the values of 2 players, then compare the winner vs player 3.
Design an enum Choice (ROCK, PAPER, SCISSORS), where each enum has a Set<Choice> which it wins against.
Have each of your players choose one of the choices.
Iterate through your players, and for each one, iterate over all the other players that are after him in the list of players (for player 0, iterate through players 1, 2, 3, etc; for player 1, iterate through players 2, 3, etc.; ...).
For each match, you have three possibilities:
A beats B (the choice of B is in the set of choices that A beats): increment A's score
A and B have the same choice: do nothing
A doesn't beat B: increment B's score
I suggested a better design in an answer to another post. Have a single switch, and switch over a single encoding of every possible combination of moves, and for an encoding use a positional number system with a base that's a power of 2, so that each digit will map directly to a number of bits, and so that bitwise manipulations are intuitive.
Three bits are sufficient for five choices, and although octal would be ideal, the syntax sucks, so use hex. Each hexadecimal digit then represents one of your five moves, with room to spare. A byte is large enough two encode the simultaneous moves of two players, an int for eight, a long for sixteen. It's straightforward. Follow the link for a code example.
This is a basic logic problem. It is small enough you can do a manual truth table ( or skip ahead to a k-map), minimize and get a solution.
So basically, you need to evaluate first, if it is a draw. Then, you need to evaluate winning relative to other players. Doing this without needing to compare against each user can be a confusing task. Since this only has 5 variables, you can find a minimized solution with a K-map.
You will need to evaluate each user, based on which item they chose with a specific algorithm to determine if they win. Note that with more than 2 players, there can be more than one winner if two people choose the same thing but both beat a 3rd player. Or you can consider that a tie, whatever. I'll assume the former. You should check also that all players didn't choose the same item.
So I've done the first part of the algorithm for you when the user you are evaluating has chosen "rock".
In code, this would look like:
rock=0, paper=0, scissors=0, lizard=0, spock=0, win=0, tie=0
if ( someone chose rock ) rock=1
if ( someone chose paper ) paper=1
if ( someone chose scissors ) scissors=1
if ( someone chose lizard ) lizard=1
if ( someone chose spock ) spock=1
// Check if tie / draw, double check these, but I think I got them all
tie=rock && !paper && spock && lizard || rock && paper && scissors ||
rock && paper && lizard || spock && paper && scissors ||
spock && !rock && paper && lizard || !spock && scissors && lizard && paper
if ( tie ) die()
CheckIfUserWins() {
if ( user chose rock ) {
win=rock && !paper && !spock
if ( user chose paper) {
// .... calculate using k-map and fill in
}
return win
Notice that win=rock && !paper && !spock is exactly what would be expected based on the graphic of what beats what at the link you provided. So you can go to that graphic and pretty quickly fill in the rest of the equations.
This solution is not dependent on any number of players other than to say "someone chose X". So it should scale to > 5 players, etc.
The shortest way:
var n = 5; // Rock, Paper, Scissors, Lizard-Spock
function calculate(x, y, n) {
return 1 - ((n + x - y) % n) % 2;
}
function getWinner(p1Gestrure, p2Guesture) {
if(p1Gestrure === p2Guesture) {
return - 1; // tie
}
return this.calculate(p1Gestrure, p2Guesture); // 0: win for p1. 1: win for p2.
}
I've created a cli game, please feel free to take a look there.
https://github.com/julianusti/rpc-es6

Categories

Resources