Java: Do-while loop with multiple conditions - java

I am trying to create the scissors-paper-stone-game in Java with a do-while loop. The computer will randomly select 1, and the user makes his choice. The exit condition is if the user wins twice (userWin) or the computer wins twice (compWin). If there is a draw, neither counter increases.
// Scissors, paper, stone game. Best of 3.
// scissors = 0; paper = 1; stone = 2;
import java.util.Scanner;
public class Optional2 {
public static void main(String[] args) {
int userWin = 0;
int compWin = 0;
do {
//comp choice
int comp = 1; //TEST CASE
// int comp = (int) (Math.random() * (2 - 0 + 1) + 0);
//user choice
System.out.println("0 for scissors, 1 for paper, 2 for stone");
Scanner sc = new Scanner(System.in);
int user = sc.nextInt();
//Draw
if (comp == user) {
System.out.println("Draw");
//Win =)
} else if (comp == 0 && user == 2 || comp == 1 && user == 0 ||
comp == 2 && user == 1) {
System.out.println("WIN!");
userWin++;
//Lose =(
} else {
System.out.println("Lose =(");
compWin++;
}
} while (compWin < 2 || userWin < 2);
System.out.println("You won " + userWin + " times!");
}
}
For int comp, it should be random, but I am setting it to 1 (paper) for easy testing.
However, presently only the 1st condition will exit the loop if it becomes true. I am expecting the 2nd condition to exit the loop too if it becomes true with the || operator, but the loop just keeps looping even if it comes true.
ie. if I put while (userWin < 2 || compWin < 2), it will exit if the user wins twice but not if the computer wins twice. If I put while (compWin < 2 || userWin < 2), it will exit if the computer wins twice but not if the user wins twice.
I tried changing it to while ((userWin < 2) || (compWin < 2)) too but it doesn't work.

but the loop just keeps looping even if it comes true
A while loops keeps looping as long as the condition remains true.
I think the problem is that you should rewrite the condition to:
while ((userWin < 2) && (compWin < 2))
with && instead of ||. Indeed: now the while loop is something like: "Keep looping as long as the the user has not won two or more times, and the computer has not won two or more times."

You should use && instead:
while (userWin < 2 && compWin < 2);
This is because you want to be in the loop as long as none of the user or comp gets 2 consecutive wins
That is translated into
userWin < 2 && (=AND) compWin < 2
Which means: as long as both the user AND the comp has less than 2 consecutive wins, stays in the loop.
Or in other words, as you have phrased it: if any of user or comp gets two consecutive wins, gets out from the loop.

Try replace with &&. You need both less that 2 to keep loop going on

Related

Do-While loop doesn't terminate when condition is false

This is a game where you can take biscuits from barrels, either from barrel1, barrel2, or both. The last player to take the last biscuits wins the game. I implemented the game in a do-while loop so that it loops every turn. However, once the number of biscuits in both barrels = 0, the loop doesn't terminate and keeps on taking scanner input.
N.B. This is coursework for university, so please do not tell me exactly what to do or give me exact code, just suggestions or why my code is not working.
import java.util.Scanner;
public class LastBiscuit {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int barrel1 = 6;
int barrel2 = 8;
// Simple turn counter. incremented every loop. if even, player 2 turn
int turnCounter = 0;
do {
turnCounter++;
int howMany = 20;
String turnAction;
// prints out biscuits left in each barrel
String output1 = String.format("Biscuits Left - Barrel 1: %d",barrel1);
String output2 = String.format("Biscuits Left - Barrel 2: %d",barrel2);
System.out.println(output1);
System.out.println(output2);
// Check turn counters value. If even, it is player 2 turn, else player 1 turn.
if (turnCounter % 2 == 0) {
System.out.println("Player Turn: 2");
}
else {
System.out.println("Player Turn: 1");
}
// Player picks what action to take in their turn. Stored in turnAction. Only allows correct input
System.out.print("Choose a barrel: barrel1 (one), barrel2 (two), or both (both), or skip turn (skip)?");
do {
turnAction = in.next();
} while (!turnAction.equalsIgnoreCase("one") && !turnAction.equalsIgnoreCase("two") &&
!turnAction.equalsIgnoreCase("both") && !turnAction.equalsIgnoreCase("skip"));
// Player picks how many biscuits to take, if at all. If biscuits taken larger than biscuits remaining,
// they have to re-enter integer
if (!(turnAction.equalsIgnoreCase("skip"))) {
System.out.print(" How many biscuits are you taking?");
while(!in.hasNextInt()) {
System.out.println("Try again");
in.next();
}
howMany = in.nextInt();
while (barrel1 - howMany < 0 || barrel2 - howMany < 0 || howMany <= 0) {
howMany = in.nextInt();
}
}
// Takes biscuits from barrels chosen
if (turnAction.equalsIgnoreCase("one")) {
barrel1 -= howMany;
}
if (turnAction.equalsIgnoreCase("two")) {
barrel2 -= howMany;
}
if (turnAction.equalsIgnoreCase("both")) {
barrel1 -= howMany;
barrel2 -= howMany;
}
// do nothing on skip
} while (barrel1 > 0 || barrel2 > 0);
//bug? doesnt print? outside of do-while loop
// doesnt exit loop?
System.out.println("YOYYYOOYOY");
if (turnCounter % 2 == 0) {
System.out.println("Player 2 Wins! ");
}
else {
System.out.println("Player 1 Wins! ");
}
}
}
You have an infinite while loop running at:
while (barrel1 - howMany < 0 || barrel2 - howMany < 0 || howMany <= 0) {
howMany = in.nextInt();
}
This only happens when you require more biscuits than a barrel contains or you request a negative number of biscuits. When it does you will be forever in this while loop.
Place a breakpoint at howMany = in.nextInt(); as already suggested and you will see it happening.

How to get do-while statement to loop infinitely with nested if statment

I am having a user enter in a multiple of 3 between 3 and 24 inclusive. The output then prints out the number less 3 until it reaches 0. Ex the user picks 15. The output prints out 15,12,9,6,3,0. The problem is if the user picks the number 17 it rounds it down to 15 and proceeds to do the rest of the code. How do I make it repeat the input infinitely if they do not enter in a multiple of 3? My code is as follows.
do{
System.out.print("Enter a multiple of 3: ");
//We use the variable n to hold the multiple of 3, like the heading says to do.
n = input.nextInt();
if (n % 3 !=0 || n >= 25) {
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
n = input.nextInt();
}
/**
* X = n /3, this gives us the base number of the multiple of 3 to use and figure out the
* values of n->0 by 3's.
*/
for(x = n / 3; x <= 8 && x >=0; x--){
int three = 3 * x;
System.out.printf(three + "\t");
}
}while(x >= 0);
As you can see I just put another input section within the if statement, however I do not wish to do this. I am trying to figure out a way for the if statement to keep looping. Is it my parameters I set up on my if statement? Or is there a specific command to make the if statement repeat if the criteria of the statement is not met? Also I am using Java.
You can use a separate loop to initialize n. (I'm not sure what your outer loop is for, so I deleted it.)
int n;
while (true) {
System.out.print("Enter a multiple of 3: ");
n = input.nextInt();
// Validate input.
if (n % 3 == 0 && n < 25 && n > 0) {
// Input is good.
break;
}
// Input is bad. Continue looping.
System.out.println("Error: Enter a multiple of 3 between 3 and 24, inclusive.");
}
for (x = n / 3; x <= 8; x--) {
int three = 3 * x;
System.out.printf(three + "\t");
}
The if--break pattern is necessary because you need to check the looping condition in the middle of the loop, rather than the beginning or end.
If you don't like the while(true) { ... break; ... } then you can use a do { ... } while (flag); loop instead. A do/while loop is common when you want to do something 1 or more times - specifically at least once and you aren't sure how many times.
For example
boolean keepGoing = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
keepGoing = (n < 3 || 24 < n || n % 3 != 0);
} while (keepGoing);
System.out.println("You entered: " + n);
Or this variation
boolean done = true;
do {
System.out.println("Enter a multiple of 3 between 3 and 24: ");
n = input.nextInt();
done = (3 <= n && n <= 24 && n % 3 == 0);
} while (!done);
System.out.println("You entered: " + n);

Java working out which number hits zero first

I'm building a simple fighting game to test out loops and if statements, however I've run into a kind of complex logic issue.
The loop ends when either the player or enemy HP hits zero however I've discovered that my code can't detect which HP hits zero first results in the player always winning.
Is there a simple way of tracking which number hits zero first therefor breaking the loop?
do {
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in);
System.out.println("1: Attack. 2: Defend");
int n = reader.nextInt();
if (n == 1){
PHP = (PHP-EATK);
EHP = (EHP-PATK);
} else if (n == 2){
PHP = (PHP-Math.max(0, EATK-PDEF));
}
System.out.println("P "+PHP);
System.out.println(EHP);
}
while (PHP >= 1 || EHP >= 1);
if(PHP <= 0){
System.out.println("You Lose!");
}else if (EHP <= 0){
System.out.println("You win!");
}
Look at your loop continuation condition:
while (PHP >= 1 || EHP >= 1)
It means "while the player or his enemy can fight, go on". In other words, you continue fighting until they both die, at which point you declare the player the winner, even though it's a draw.
Changing the condition to ""while the player and his enemy can fight" will fix this problem.
change while (PHP >= 1 || EHP >= 1); to while (PHP >= 1 && EHP >= 1);.
You using OR operation where you want AND

Java Conditions Confusion? (Beginner)

The aim of this program is to make a Rock Paper Scissors game. I have succeeded in making it however I can not get it to loop no matter what I try. I tried:
while (index = 0)
while (index < gamesCount)
However, while my index is 0 and my condition says while (index != 0), it seems to be the only condition that runs the program but it will not loop regardless. How can I get my game to loop?
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random randomGen = new Random();
//Variables
String player1;
int cpu;
int start = 1;
int end = 3;
int index = 0;
// 1 = Rock | 2 = Scissors | 3 = Paper
//Code
System.out.println("Welcome to Rock, Paper, Scissors!");
while (index != 0) {
System.out.print("Rock, Paper, or Scissors?: ");
player1 = in.nextLine();
cpu = randomGen.nextInt(3);
System.out.println(cpu);
if (player1.equals("Rock") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Rock") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Rock") && (cpu == 0)) {
System.out.println("Draw!");
}
// --------------------
if (player1.equals("Scissors") && (cpu == 2)) {
System.out.println("Draw!");
} else if (player1.equals("Scissors") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Scissors") && (cpu == 0)) {
System.out.println("You lose!");
}
//---------------------
if (player1.equals("Paper") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Paper") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Paper") && (cpu == 0)) {
System.out.println("Draw!");
}
}
}
}
You have your index variable set to 0. The condition of the while loop is saying, if index does not equal 0, execute the code in the loop. Since your index equals 0, the instructions in the loop will not be executed. Also, you will need to update the index variable in the loop so that if the condition you are looking for is met, the code will stop looping.
ie:
int gamesPlayed = 0;
int gamesRequested = 3; // or get this from the user
while (gamesPlayed < gamesRequested){
String player1Choice = in.nextLine();
if(!"".equals(player1)){
// your code
gamesPlayed++;
} else {
System.out.print("Rock, Paper, or Scissors?: ");
}
}
Two mistakes:
while (index != 0);
this is the entire loop. it ends either at the end of the { } block (which you don't have), or at the first ; which is immediately after the statement.
Correct this, though, and it still won't loop:
int index = 0;
// 1 = Rock | 2 = Scissors | 3 = Paper
//Code
System.out.println("Welcome to Rock, Paper, Scissors!");
while (index != 0);
index = 0, so (index != 0) will never return true.
Your index variable is set to a value of 0.
Your while loop says
while (index != 0);
Which means, while the index isn't 0, run my code. The problem is your code will never run then because your index value is always 0.
Try changing it to another value (say 5 for example), and it should work now.
:)

Math.random if statement error

int Comproll1= (int) (Math.random()*6+1);
int Comproll2= (int) (Math.random()*6+1);
while (m==1)
{
{
if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
else if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
else
{
cr= Comproll1+Comproll2;
cp= cp+cr;
}
}
Hey everyone! Above is my code- for some reason regardless, it WILL ALWAYS, no matter what, always display the first option, which is "One of the computer's dice rolls was a 1, it lost all points for the round...". Even when I change the order of the statements, it still does this. Can someone please explain to me why this is happening?? Thanks!
As far as I can tell, because you aren't re-rolling
int Comproll1= (int) (Math.random()*6+1);
int Comproll2= (int) (Math.random()*6+1);
while (m==1)
{
Should be
while (m==1)
{
int Comproll1= (int) (Math.random()*6+1);
int Comproll2= (int) (Math.random()*6+1);
Also, Java naming convention is camel case for variables (and starts with a lower case letter). So, Comproll1 might be compRoll1. Finally, I personally prefer Random.nextInt() and for 6 sided dice that might look like
Random rand = new Random();
while (m==1)
{
int compRoll1 = rand.nextInt(6) + 1;
int compRoll2 = rand.nextInt(6) + 1;
Edit Actually, you also need to reverse the order of your tests. Because if either is true then it will never be possible that the test for both being true will be entered.
if (Comproll1==1 || Comproll2==1) {
// Here.
}else if (Comproll1==1 && Comproll2==1) {
// Will never enter here.
}
Switch the order to,
if (Comproll1==1 && Comproll2==1) {
// Both.
}else if (Comproll1==1 || Comproll2==1) {
// Either.
}
The problem is that you need to check if they are both 1, before checking if either of them are 1s. If we look at the code:
if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
else if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
if:
Comproll1 = 1
Comproll2 = 1
You expect that it will go into the else if (Comproll1==1 && Comproll2==1) however, if this is true than if (Comproll1==1 || Comproll2==1) will always be true.
To fix this simply change the order of the ifs, like this:
if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
else if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
Hope this helps :)
(Also you need to reroll the dice (as Elliott Frisch Said in his answer))
Try changing the order of your if statements. Logically, if one of the two comparisons are true, the first statement will execute. In the case that the second conditions else if (Comproll1==1 && Comproll2==1) are true, the first conditions if (Comproll1==1 || Comproll2==1) will also be true.
Since you've chained the if statements in an if-else-if fashion, the first if statement to equate to true will execute.
if (Comproll1==1 && Comproll2==1)
{
System.out.println("The Computer rolled 2 1's, their total number of points is now 0 & it is now your turn!");
cp=cp-cp;
m++;
}
else if (Comproll1==1 || Comproll2==1)
{
System.out.println("One of the computer's dice rolls was a 1, it lost all the points for the round & it is now your turn!");
cr= cr-cr;
m++;
}
else
{
cr= Comproll1+Comproll2;
cp= cp+cr;
}

Categories

Resources