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.
:)
Related
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.
I just started coding with more complex methods than the main method. I was given an assignment to make a race with three coins. Whichever coin flips 2 heads and 2 tails first in that order wins. I coded an if else statement to determine which coin wins but neither of the if statements are ever executed. Please tell me if you see an error in my if else statements or somewhere else. I also have to other programs of code that include other methods.
public class FlipRace
{
public static void main (String[] args)
{
final int GOALHEAD = 2;
final int GOALTAIL = 2;
int count1 = 0, count2 = 0, count3 = 0, count10 = 0, count20 = 0, count30 = 0;
// Create three separate coin objects
Coin coin1 = new Coin();
Coin coin2 = new Coin();
Coin coin3 = new Coin();
while (count1 <= GOALHEAD && count10 <= GOALTAIL || count2 <= GOALHEAD && count20 <= GOALTAIL || count3 <= GOALHEAD && count30 <= GOALTAIL)
{
coin1.flip();
coin2.flip();
coin3.flip();
// Print the flip results (uses Coin's toString method)
System.out.print ("Coin 1: " + coin1);
System.out.println (" Coin 2: " + coin2);
System.out.println (" Coin 3: " + coin3);
// Increment or reset the counters
if (coin1.isHeads())
count1++;
else
count10++;
if (coin2.isHeads())
count2++;
else
count20++;
if (coin3.isHeads())
count3++;
else
count30++;
}
// Determine the winner
if (count1 == GOALHEAD && count10 == GOALTAIL)
System.out.println ("Coin 1 wins!");
else if (count2 == GOALHEAD && count20 == GOALTAIL)
System.out.println ("Coin 2 wins!");
else if (count3 == GOALHEAD && count30 == GOALTAIL)
System.out.println ("Coin 3 wins!");
else
System.out.println ("It's a TIE!");
}
}
Here is my output:
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Heads
Coin 3: Heads
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
It's a TIE!// this message comes up every time because something is wrong
try changing your comparison to
if (count1 >= GOALHEAD && count10 >= GOALTAIL)
System.out.println ("Coin 1 wins!");
else if (count2 >= GOALHEAD && count20 >= GOALTAIL)
System.out.println ("Coin 2 wins!");
else if (count3 >= GOALHEAD && count30 >= GOALTAIL)
System.out.println ("Coin 3 wins!");
else
System.out.println ("It's a TIE!");
of course another way would to simply debug your code and inspect the values
I don't understand how your code would solve the problem. If I understand it right, you want the first coin that shows the combination H-H-T-T. Now, you are counting the heads and tails in ANY order. So, if you have H-T-H-T for the first coin and H-H-H-T and H-T-T-T for the second and third respectively, the first one wins.
In order to solve the problem considering the order of heads and tails, I think you should change the if-else statement for each coin (I'll make it only for coin1 here):
if (coin1.isHeads()) {
if (count1 < 2 && count2 == 0) { //less than 2 heads and zero tails
count1++;
} else {
count1 = 0;
count10 = 0;
}
} else { //tails
if (count1 == 2 && count10 < 2) { //we already have two heads and 0 or 1 tail
count10++;
} else { // either less than two heads or too many tails - we have to restart!
count1 = 0;
count10 = 0;
}
}
You should also change the while statement... You want to stop when you have two heads ant two tails for any coin. So, it'd be something like this:
while (!(count1 == 2 && count10 == 2) && !(count2 == 2 && count20 == 2) && ....) {...}
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
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
In a blackjack game I give a user prompt to choose if he wants to double down:
while(true){
if(players[i].doubledown == true){
break;
}
System.out.println("Want to double down?\n1)Yes\n2)No\n");
dd = IO.readInt();
if (dd != 1 && dd!= 2){
IO.reportBadInput();
}else{
break;
}
}
int x = 0;
if (dd!=1 && players[i].doubledown == false){
System.out.print("Choose your next move, " + players[i].name + ": \n" + "Points: " + players[i].points + "\n" + "Hint: ");
getHints(players[i]);
System.out.print( "\n1)Hit\n2)Stand\n");
System.out.println();
x = IO.readInt();
}else if(dd == 1 && players[i].doubledown == true){
x = 2;
}else if( dd== 1 && players[i].doubledown == false){
x = 1;
players[i].doubledown = true;
}
if(x ==2 || x ==1){
//
//Stand or Bust
//
}
For some reason it keeps asking me to double down and then after that it's player 2's turn. Why? Any help will be appreciated.
This code will always ask the player to double down, if players[i].doubledown is false. You don't show us the code where you set that flag, so I assume it's always false if it keeps asking you.
If you then answer 1, it goes into the 3rd case of your if statement, which doesn't print anything, so I assume that would make it player 2's turn. If you answer 2, it should ask you to hit or stand... does that happen?