Loop and conditionals not working properly [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
If I do not roll a 1, and I would like to "hold" my roll. The code ignores the instructions within the "h" bracket conditional statement, and rolls the dice again. I am confused because if I do roll a 1, the code does work and goes to the computer's turn, setting the flags correctly.
while ((humanScore <= 100) && (computerScore <=100))
{
/*loop while human turn is true*/
while ((humanTurn == true) && (computerTurn == false))
{
die = randomGenerator.nextInt(6) + 1;
if(die == 1)
{
System.out.println("Human, you rolled a 1, you lose your points and your turn.");
humanTurn = false;
computerTurn = true;
points = 0;
System.out.println("Your score is now " + humanScore);
System.out.println("Computer, it is now your turn.");
}
else if(die != 1)
{
System.out.println("Human, you currently have " + points + " points to add to score.");
System.out.println("You have rolled a " + die + " would you like to hold, or roll again?");
System.out.println("Please enter either r to roll, or h to hold.");
points = points + die;
decision = scanner.next();
if (decision == "r")
{
humanTurn = true;
}
if(decision == "h")
{
humanScore = humanScore + points;
humanTurn = false;
computerTurn = true;
points = 0;
System.out.println("You hold, your score is now " + humanScore);
System.out.println("Computer, it is now your turn.");
}
}
}

if (decision.equals("r"))
{
humanTurn = true;
}
if(decision.equals("h"))
{
humanScore = humanScore + points;
humanTurn = false;
computerTurn = true;
points = 0;
System.out.println("You hold, your score is now " + humanScore);
System.out.println("Computer, it is now your turn.");
}

Related

Updating Parameter Value in Java

I wasn't too sure what to title this so I apologize in advance. I am currently trying to make a game where the total points must add up to 100 for a player to win. I am running into the issue where the "PlayerTotalPoints" is not updating after the PlayerTurn method returns the amount of PlayerTotalPoints and sets that as the new value in PlayerTotalPoints to be rerun in the method once again.
This is my code:
public static void main(String[] args) {
int PlayerTotalPoints = 0;
int ComputerTotalPoints = 0;
while (!IsGameOver(PlayerTotalPoints, ComputerTotalPoints)) {
int TurnPointCounter = 0;
System.out.println("It is the player's turn!");
PlayerTotalPoints = PlayerTurn(TurnPointCounter, PlayerTotalPoints);
System.out.println("The player currently has " + PlayerTotalPoints + " total points!");
System.out.println("It is the computer's turn!");
ComputerTotalPoints = ComputerTurn(TurnPointCounter, ComputerTotalPoints);
System.out.println("The computer currently has " + ComputerTotalPoints + " total points!");
}
}
The method PlayerTurn returns the new value of the PlayerTotalPoints (I checked and it is returning the correct value of PlayerTotalPoints) but for some reason this value is not carrying over to the PlayerTotalPoints variable which needs to keep going as a player accumulates their score. This is for an assignment so I am not sure how much of my code I am allowed to share online but if you need more examples of my code just let me know, thanks.
EDIT: These are the PlayerTurn and ComputerTurn methods:
public static int PlayerTurn(int counter, int PlayerTotalPoints) {
System.out.println("The player currently has " + counter + " turn points.");
System.out.println("Do you want to play or hold this turn? (P/H)");
String answer = scan.nextLine();
answer = answer.replaceAll(" ", "");
answer = answer.toUpperCase();
if (answer.equals("H")) {
PlayerTotalPoints += counter;
System.out.println("You have elected to hold this turn.");
// System.out.println("You currently have " + PlayerTotalPoints + " total points.");
System.out.println(PlayerTotalPoints);
return PlayerTotalPoints;
}
int[] OneRoll = RollDice();
int TurnCount = Turn(OneRoll, counter);
if (OneRoll[0] == 6 && OneRoll[1] == 6) {
PlayerTotalPoints = 0;
return PlayerTotalPoints;
}
if (OneRoll[0] == 6 | OneRoll[1] == 6) {
// System.out.println("The player currently has " + PlayerTotalPoints + " total points.");
return PlayerTotalPoints;
}
PlayerTurn(TurnCount, PlayerTotalPoints);
return PlayerTotalPoints;
}
public static int ComputerTurn(int counter, int ComputerTotalPoints) {
System.out.println("The computer currently has " + counter + " turn points.");
int n = generator.nextInt(100);
if (n >= 70) {
ComputerTotalPoints += counter;
System.out.println("The computer has decided to hold this turn. ");
// System.out.println("The computer currently has " + ComputerTotalPoints + " total points.");
return ComputerTotalPoints;
}
int[] CompRoll = RollDice();
int CompTurnCount = Turn(CompRoll, counter);
if (CompRoll[0] == 6 && CompRoll[1] == 6) {
ComputerTotalPoints = 0;
return ComputerTotalPoints;
}
if (CompRoll[0] == 6 | CompRoll[1] == 6) {
// System.out.println("The computer currently has " + ComputerTotalPoints + " total points.");
return ComputerTotalPoints;
}
ComputerTurn(CompTurnCount, ComputerTotalPoints);
return ComputerTotalPoints;
}
Shouldn't the following:
PlayerTurn(TurnCount, PlayerTotalPoints);
return PlayerTotalPoints;
be something like
PlayerTotalPoints = PlayerTurn(TurnCount, PlayerTotalPoints);
return PlayerTotalPoints;
For both PlayerTurn and ComputerTurn method calls? Remember, this is a recursive call.

Why is my program looping twice more than needed?

I am completely new to programming and I was making a program for class. For the project, I need to make a "self directed" program. I wanted to make a simple program; I wanted a fighting simulator! So the point of the program is to do this:
Introduce you, and start the fight. The attack is completely random out of 5, and you and the "enemy" fight until one of you hits 0 hp. I want the program to end, and display the health of you and your enemy and tell you if you have won or not. Pretty simple, but it's harder than you'd think especially with the lack of programming I have learned. I just need help fixing it or simplifying it. Thanks for the information if you can help! Code below:
import java.util.Scanner;
public class TG_UN4EX13 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String rumble = "startvalue";
System.out.println("Welcome to the Ultimate Battle Game!");
System.out.println("Have Fun!");
// Attack Section //
int attack1 = 5;
int attack2 = 10;
int attack3 = 20;
int attack4 = 40;
int cower = 0;
// Character Section//
int playerhealth = 100;
// Character Section//
// Enemy Section//
int enemyhealth = 100;
// Enemy Section//
while (playerhealth >= 0 || enemyhealth >= 0 || rumble.equalsIgnoreCase("Yes")) {
int attacknumber = (int) (Math.random() * (5 - 1 + 1) + 1);
int attacknumber2 = (int) (Math.random() * (5 - 1 + 1) + 1);
if (attacknumber == 1) {
enemyhealth = enemyhealth - attack1;
System.out.println("You used Punch!");
System.out.println("You did " + attack1 + " damage! \n");
} else if (attacknumber == 2) {
enemyhealth = enemyhealth - attack2;
System.out.println("You used Kick!");
System.out.println("You did " + attack2 + " damage! \n");
} else if (attacknumber == 3) {
enemyhealth = enemyhealth - attack3;
System.out.println("You used Jab!");
System.out.println("You did" + attack3 + " damage! \n");
} else if (attacknumber == 4) {
enemyhealth = enemyhealth - attack4;
System.out.println("You used Roundhouse Kick!");
System.out.println("You did " + attack4 + " damage! \n");
} else if (attacknumber == 5) {
enemyhealth = enemyhealth - cower;
System.out.println("You cowered in fear!");
System.out.println("You did " + cower + " damage! \n");
}
if (attacknumber2 == 1) {
playerhealth = playerhealth - attack1;
System.out.println("They used Punch!");
System.out.println("They did " + attack1 + " damage! \n");
} else if (attacknumber2 == 2) {
playerhealth = playerhealth - attack2;
System.out.println("They used Kick!");
System.out.println("They did " + attack2 + " damage! \n");
} else if (attacknumber2 == 3) {
playerhealth = playerhealth - attack3;
System.out.println("They used Jab!");
System.out.println("They did " + attack3 + " damage! \n");
} else if (attacknumber2 == 4) {
playerhealth = playerhealth - attack4;
System.out.println("They used Roundhouse Kick!");
System.out.println("They did " + attack4 + " damage! \n");
} else if (attacknumber2 == 5) {
playerhealth = playerhealth - cower;
System.out.println("They cowered in fear!");
System.out.println("They did " + cower + " damage! \n");
}
System.out.println("You have " + playerhealth + " health!");
System.out.println("They have " + enemyhealth + " health! \n");
}
if (playerhealth > enemyhealth) {
System.out.println("You won!");
System.out.println("Do you want to play again?");
rumble = scan.nextLine();
} else {
System.out.println("You lost!");
System.out.println("Do you want to play again?");
rumble = scan.nextLine();
}
if (rumble.equalsIgnoreCase("no")) {
System.out.println("Well, goodbye!");
System.exit(0);
}
}
}
P.S. This is a quick edit but here is an example:
You have 20 health! They have 20 health!
You used Jab! You did20 damage!
They used Roundhouse Kick! They did 40 damage!
You have -20 health! They have 0 health!
You used Jab! You did20 damage!
They used Roundhouse Kick! They did 40 damage!
You have -60 health! They have -20 health!
You lost! Do you want to play again?
I'm not positive, but I think you may need to change:
while(playerhealth>=0 || enemyhealth>=0 || rumble.equalsIgnoreCase("Yes"))
to
while((playerhealth>0 && enemyhealth>0) || rumble.equalsIgnoreCase("Yes"))
If the health is =0, it will run again, so remove the = as well
Take a look at the conditions for your loop.
while (playerhealth >= 0 || enemyhealth >= 0 || rumble.equalsIgnoreCase("Yes")) {
//do stuff
}
You're saying, "Keep fighting while any of the following conditions are true":
Player health is positive
Enemy health is positive
Rumble = Yes
Now think about what it will take to exit that loop (ie, end the game).
Exiting the loop is the opposite of staying in the loop, so you want the opposite of those conditions, which is, "Stop fighting when all of the following are true":
Player health is less than 0
Enemy health is less than 0
Rumble != Yes
Do you mean for the fight to only end when both the player and enemy have negative health, or should it end when either the player or the enemy have negative health?

trying to understand my error in my pig java game

I am working on my final project for my intro to java class and i am having a hard time understanding the errors in my project and why it will not run if you could tell me why i would greatly appreciate it
public static void main(String[] args) {
Scanner scanner1;
int dice, dice2;
int pScore, cScore = 0;
int pTotalScore = 0;
int cTotalScore = 0;
final int maxScore = 750;
String input = "R";
String input2 = "R";
char repeat;
Random randomNumbers = new Random();
System.out.println("Welcome to Our version of the dice game Pig");
System.out.println("Here are the instructions");
System.out.println("On a turn, the player or computer rolls the die repeatedly");
System.out.println("Until either a 1,7,12, or 17 is rolled");
System.out.println("or the player or computer holds");
System.out.println("If a 1,7,12, or 17 is rolled, that player's turn ends");
System.out.println("and no points are earned");
System.out.println("If the player chooses to hold, all of the points rolled during");
System.out.println("that turn are added to his or her score.");
System.out.println("First player to 750 points or more WINS!");
System.out.print("\nPlease enter your name: ");
scanner1 = new Scanner(System.in);
String pName = scanner1.nextLine();
System.out.print("\nI Hope You have fun," + pName);
do { // run at least once. Start of loop
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.printf("%s you rolled a %d %n", pName, dice);
if (dice == 1 || dice == 7 || dice == 12 || dice == 17) // if these numbers, end
{
pScore = 0;
System.out.println("Turn over.");
System.out.println(" " + pName + " total is " + pScore + " ");
break;
} else { // else ask for re-roll
pScore = dice;
pTotalScore += pScore;
System.out.print(+pScore + " Your turn total is " + pTotalScore + " ");
System.out.print("Enter (R) to roll or (H)to hold: ");
input = scanner1.nextLine();
repeat = input.charAt(0);
}
if (repeat != 'R') { // if something other than R, end
break;
}
} while (pTotalScore < 750 || cTotalScore < 750); // allow repeat so long as scores are less than 750
if (repeat == 'H') {
System.out.println("Turn over.");
System.out.print("Current score: " + pname + " has " + pTotalScore);
System.out.println("The Computer has " + cTotalScore);
break;
}
while (input.equalsIgnoreCase("R"));
if (pTotalScore >= maxScore) {
System.out.println("Your total Score is " + totalScore);
System.out.println(+pname + "WINS!");
break;
}
System.out.println();
System.out.println("It is the Computer's turn.");
do {
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The Computer rolled: " + dice2);
if (dice2 == 1 || dice2 == 7 || dice2 == 12 || dice2 == 17) {
cScore = 0;
System.out.print("Turn over");
System.out.println("The Computer total is " + cTotalScore);
break;
} else {
cScore = dice2;
cTotalScore += cScore;
System.out.print("The Computer's total is " + cTotalScore + " ");
System.out.print("Enter (r) to Roll or (H)to Hold: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
if (repeat == 'H') {
System.out.println("Turn over");
System.out.print("Current score:" + pName + " has " + pTotalScore);
System.out.println(", The Computer has " + cTotalScore);
break;
}
} while (input2.equalsIgnoreCase("R"));
if (cTotalScore >= maxScore) {
System.out.println("The Computer's score is " + cTotalScore + "\n");
System.out.println("The Computer wins!!!!");
System.out.printl("Run The uprisng has begun!!!!!!");
break;
}
Final3.java:112: error: reached end of file while parsing } ^ 1 error
now the problem is i get the error basically means im missing a } but i cant see where it would be nd no matter where i put it it still says
Final3.java:112: error: reached end of file while parsing } ^ 1 error
You have one while loop that does nothing - while (input.equalsIgnoreCase("R")); - and you didn't close your main method. Add } at the end.
Add a closing brace "}" in the end.I hope this will solve your purpose.

Making a Pig Game using Object Oriented Programming (Java)

Hey guys so I made a Pig Game in Java for my CS project. I didn't have too much trouble with it because I only used one class. However, my professor now is making us implement OOP, and I'm having a lot of trouble. Here is my working Pig Game:
package edu.bsu.cs121.zmbarnes;
import java.util.Random;
import java.util.Scanner;
public class PigGame {
public static void main(String[] args) {
int player1TurnScore = 0;
int player1TotalScore = 0;
int player2TurnScore = 0;
int player2TotalScore = 0;
int dice;
int dice2;
String input = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Random diceRoll = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(player1TotalScore < 100 || player2TotalScore < 100){
// human's turn
System.out.println();
System.out.println("It is Player 1's turn.");
do{
dice = diceRoll.nextInt(6) + 1;
System.out.println("You rolled a " + dice);
if(dice == 1){
player1TurnScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + player1TotalScore);
break;
}else{
player1TurnScore += dice;
System.out.println("Your turn score is " + player1TurnScore);
System.out.println("And your total score is " + player1TotalScore);
System.out.println("If you hold, " + player1TurnScore + " points will be added to your total score.");
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
}while(input.equalsIgnoreCase("r") || dice != 1);
player1TotalScore += player1TurnScore;
System.out.println("Your score is " + player1TotalScore);
player1TurnScore = 0;
if(player1TotalScore >= 100){
System.out.println("Your total score is " + player1TotalScore);
System.out.println("PLAYER 1 WINS!");
break;
}
// Player 2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
do{
dice2 = diceRoll.nextInt(6) + 1;
System.out.println("You rolled a " + dice2);
if(dice2 == 1){
player2TurnScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + player2TotalScore);
break;
}else{
player2TurnScore += dice2;
System.out.println("Your turn score is " + player2TurnScore);
System.out.println("And your total score is " + player2TotalScore);
System.out.println("If you hold, " + player2TurnScore + " points will be added to your total score.");
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
}while(input.equalsIgnoreCase("r") || dice2 != 1);
player2TotalScore += player2TurnScore;
System.out.println("Your score is " + player2TotalScore);
player2TurnScore = 0;
if(player2TotalScore >= 100){
System.out.println("Your total score is " + player2TotalScore);
System.out.println("PLAYER 2 WINS!");
break;
}
}
keyboard.close();
}
}
I must use a Dice class with a roll() method, a Player class with void takeTurn(), void bankPoints(), void makeChoice(), and boolean hasWon() methods, a GameOfPig class with , and Project class with void play() method, and the main Project class with main().
I'm just having trouble conceptualization how I can move my code into those methods so the game will work the exact same way. Any help would be appreciated!
I'm also new to OOD. My brief answer is highly borrowed from your code. I hope other one could correct me. Any suggestion is appreciated.
public class PigGame {
Dice dice;
Player player1;
Player player2;
public PigGame() {
this.player1 = new Player("Player1");
this.player2 = new Player("Player2");
this.dice = new Dice();
}
public void play() {
while (!player1.hasWon() && !player2.hasWon()) {
player1.takeTurn(dice);
if (!player1.hasWon())
player2.takeTurn(dice);
}
if (player1.hasWon()) {
System.out.println("Player1 won!");
} else {
System.out.println("Player2 won!");
}
}
public static void main(String[] args) {
PigGame pg = new PigGame();
pg.play();
}
}
class Dice {
private static Random diceRoll = new Random();
public int roll() {
return diceRoll.nextInt(6) + 1;
}
}
class Player {
private int currentRoundScore = 0;;
private int totalScore = 0;
private String playerName;
public Player(String name) {
this.playerName = name;
}
public void takeTurn(Dice dice) {
currentRoundScore = 0;
System.out.println("-------It's " + playerName + "'s turn.--------");
Scanner keyboard = new Scanner(System.in);
String input = "r";
int diceValue = 0;
do {
diceValue = dice.roll();
System.out.println("You rolled a " + diceValue);
if(diceValue == 1){
currentRoundScore = 0;
System.out.println("You lose your turn!");
System.out.println("Your total score is " + totalScore);
break;
}else{
currentRoundScore += diceValue;
System.out.println("Your turn score is " + currentRoundScore);
System.out.println("If you hold, " + currentRoundScore + " points will be added to your total score. And your total score would be " + currentRoundScore + totalScore);
System.out.println("Enter 'r' to roll again, or 'h' to hold.");
input = keyboard.nextLine();
char repeat = input.charAt(0);
if(repeat == 'h'){
break;
}
}
} while (input.equalsIgnoreCase("r") || diceValue != 1);
bankPoints();
}
public boolean hasWon() {
return totalScore >= 100;
}
public void bankPoints() {
totalScore += currentRoundScore;
System.out.println(playerName + "'s total score is " + totalScore + "\n");
}
}

boolean will not return false

import java.util.Random;
import java.util.Scanner;
public class HiLo {
/**
* Nick Jones
* 2/10/2015
* High or Low
*/
public static boolean high() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 6 && x < 14) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static boolean low() {
int x;
boolean answer;
Random randomGenerator = new Random();
x = randomGenerator.nextInt(9 - 1) + 1;
System.out.println("number is " + x);
if (x > 0 && x < 7) {
System.out.println("You win!");
answer = true;
return answer;
} else {
System.out.println("You lose!");
answer = false;
return answer;
}
}
public static void main(String[] args) {
int points = 1000;
int risk;
int guess;
boolean answer;
int again;
do {
System.out.println("you have " + points + " points.");
Scanner input = new Scanner (System.in);
System.out.println ("Input number of points to risk: ");
risk = input.nextInt();
System.out.println ("predict <1-high, 0-low>: ");
guess = input.nextInt();
if (guess == 1) {
answer = high();
} if (guess == 0) {
answer = low();
}
if (answer = true) {
points = points + (risk*2);
**} if (answer = false) {
points = points - risk;**
}
System.out.println("You have " + points + " points.");
System.out.println("play again?<yes-1, no-0> ");
again = input.nextInt();
} while (again == 1);
}
}
This program is meant to start with the player having a score of 1000 points a number is then randomly generated and they chose a amount of their score to 'risk' then chose high or low (low - 1-6. high - 8-13) if their guess is correct their risk is doubled and added back into their score. If incorrect then risk is subtracted from score. my boolean statment seems to be stopping the program from
if (answer = false) {
points = points - risk;
this part, so my boolean never returns false is what I believe my problem is. because when run it only ever allows the player to win, never to lose, it will output that 'you lose' but still add the points as if they had won.
You are using the assignment operator =, so answer is always true. The comparison operator for equality is ==, as you have already used elsewhere in your code. But answer is already a boolean. There is no need to use == to compare it; just use it. Change
if (answer = true) {
points = points + (risk*2);
} if (answer = false) {
points = points - risk;
}
to
if (answer) {
points = points + (risk*2);
} else {
points = points - risk;
}

Categories

Resources