Updating Parameter Value in Java - 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.

Related

Java program that teaches kid simple addition and subtraction

I feel like I'm almost there with the code but the problem is the while loop I am not allowed to use break and continue statements for this program. The first output test its suppose to have 14 questions where you get 12 right and 2 wrong giving you 86%. As for the second test you get a perfect score while the last test takes you to 20 questions that being the max number of questions, 4 of the first 8 questions correctly and 4 of the first 8 incorrectly, and then the next 12 correctly giving you 80% Code below:
package proj3;
import java.util.Scanner;
public class Project4App {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int correctNum = 0;
int wrongNum = 0;
double percent = 0;
int subNumCorrect = 0;
int subNumWrong = 0;
int addNumCorrect = 0;
int addNumWrong = 0;
int totalQuestions = 0;
while(!(correctNum == 10 && totalQuestions == 10) && !(percent >= 85.0 && totalQuestions >= 10) && (totalQuestions != 20)) {
Question Quest = new Question();
System.out.println("What is the result?" + "\n" + Quest.toString());
int userInt = scnr.nextInt();
if((Quest.getOperator() == '+') && (userInt == Quest.determineAnswer())) {
addNumCorrect += 1;
}
else if(Quest.getOperator() == '+' && (userInt != Quest.determineAnswer())) {
addNumWrong += 1;
}
if((Quest.getOperator() == '-') && (userInt == Quest.determineAnswer())) {
subNumCorrect += 1;
}
else if((Quest.getOperator() == '-') && (userInt != Quest.determineAnswer())) {
subNumWrong += 1;
}
if(userInt == Quest.determineAnswer()){
correctNum += 1;
System.out.println("Congratulations, you got it correct!");
}
else if (userInt != Quest.determineAnswer()){
wrongNum += 1;
System.out.println("The correct answer for " + Quest.toString() + " is " + Quest.determineAnswer());
}
totalQuestions++;
percent = Math.round((double)(correctNum * 100) / (totalQuestions));
}
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: " + percent + "%");
scnr.close();
}
}
I think this largely does what you want. A number of the counters weren't being modified as was intended. This is partly due to the amount going on in your main method making it hard to see what's going on (too much information). I've extracted functionality to smaller, more well defined methods.
You had a whole lot of logic effectively saying you want the user to have achieved 85% with at least 10 questions answered - and stop when 20 questions are asked. You could factor this condition out to a method returning a boolean isGameComplete(totalQuestions) and put this in the while condition-expression.
I've taken the liberty of implementing a question class based on the functionality that I think achieves the intention.
The correctPercent was rounded to an int which made it impossible to be == to 85.5%, say. I've converted this to a double so if you get more than 85%, say 85.25%, the game completes successfully.
Probably some other stuff I've added, which I've tried to comment in-line, if significant. Hopefully this is what you were after.
If it ever gets too difficult to understand, extracting small chunks of code to well named methods (even long ones) helps enormously, since it reduces your mental load.
class Project4App {
static final Scanner scanner = new Scanner(System.in);
static int correctNum = 0;
static int wrongNum = 0;
static int subNumCorrect = 0;
static int subNumWrong = 0;
static int addNumCorrect = 0;
static int addNumWrong = 0;
static int totalQuestions = 0;
static double percentCorrect = 0;
public static void main(String[] args) {
/**
* answer at least 9/10 questions correctly (to get 85%)
*/
while (percentCorrect < 85.0 && totalQuestions >= 10 && totalQuestions <= 20) {
Question question = new Question();
int userInt = getUsersAnswer(question);
boolean isCorrect = question.determineAnswer(userInt);
updateStatistics(question, isCorrect);
printResults(); // can remove this/comment this out - added to help with debugging
}
System.out.println();
System.out.println("------------ Game Complete! ------------");
printResults();
}
private static void printResults() {
System.out.println("\nProgress Report: " + "\nAddition:\nYou got " + addNumCorrect + " correct and " + addNumWrong + " incorrect.");
System.out.println("Progress Report: " + "\nSubtraction:\nYou got " + subNumCorrect + " correct and " + subNumWrong + " incorrect.");
System.out.println("The percent correct: (" + (addNumCorrect+subNumCorrect) + "/" + totalQuestions +") " + percentCorrect + "%");
System.out.println("The percent wrong: (" + (addNumWrong+subNumWrong) + "/" + totalQuestions +") " + (100 - percentCorrect) + "%");
}
private static int getUsersAnswer(Question question) {
System.out.println("What is the result?" + "\n" + question.toString());
int userInt = scanner.nextInt();
return userInt;
}
public static void updateStatistics(Question question, boolean isCorrect){
if (question.getOperator() == '+') {
if (isCorrect) {
addNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
addNumWrong++;
wrongNum++; // newly added - unused variable originall
}
} else { // operator is '-'
if (isCorrect) {
subNumCorrect++;
correctNum++; // newly added (wasn't updated)
} else {
subNumWrong++;
wrongNum++; // newly added - unused variable originall
}
}
totalQuestions++; // newly added
percentCorrect = (correctNum * 100) / totalQuestions;
}
}
class Question {
private static final int UPPER_LIMIT_ON_RANDOM_NUMBERS = 20;
private static final Random random = new Random();
private final int number1;
private final int number2;
private final char operator;
public Question() {
operator = Math.random()>0.5 ? '+' : '-';
number1 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // NOTE THE SUBTRACTION NUMBER COULD BE NEGATIVE IF number2
number2 = random.nextInt(UPPER_LIMIT_ON_RANDOM_NUMBERS); // IS GREATER THAN number1.
}
public char getOperator() {
return operator;
}
public boolean determineAnswer(int userAnswer) {
switch (operator) {
case '+':
return userAnswer == (number1 + number2);
case '-':
return userAnswer == (number1 - number2);
}
return false; // shouldn't end up here - would be better to throw an unchecked exception and crash the program - new RuntimeException()
}
#Override
public String toString() {
return number1 + " " + operator + " " + number2;
}
}
Output:
------------ Game Complete! ------------
Progress Report:
Addition:
You got 7 correct and 0 incorrect.
Progress Report:
Subtraction:
You got 2 correct and 1 incorrect.
The percent correct: (9/10) 90.0%
The percent wrong: (1/10) 10.0%

My pig dice game in JAVA won't save each player's score and the game doesn't stop even after reaching the score

My pig dice game for my computer science class won't save each individual score after each turn, and my game won't stop even after a player reaches the max score( I know boo leans are the cause but, I don't know what else to use). Also when a player declines to roll again the score goes back to zero. If anyone help me with this, it would be really nice!! Thank youu.
import java.util.*;
import java.util.Random;
public class PigDiceGamebyJian {
public static Scanner sc = new Scanner(System.in);
public static Random gen = new Random();
public static void main(String[] args) {
//char repeat;
System.out.println(" Welcome to the Pig Dice Game ");
System.out.println("This game requires two players");
System.out.println("How to play: each player will take turn rolling the dice (adding up the turns) until the sum is 30");
System.out.println("First one to get to 30 wins, though if on a turn, if you roll a 1, ");
System.out.println("you will give the dice to the other player, and you will not add anything to your score because 1 = 0");
System.out.println("Enough with the boring rules.");
String p1 = getName();
String p2 = getName();
System.out.println("Hello " + p1 + " and " + p2 + ".");
System.out.println("Please enter a score that you would like to play up to");
final int fin = sc.nextInt();
System.out.println(p1 + " will be going first.");
int p1score = roll(p1, 0, fin);
int p2score = roll(p2, 0, fin);
while (p1score < fin && p2score < fin ) {
p1score += roll(p1, 0, fin);
p2score += roll(p2, 0, fin);
}
}
private static int roll(String player, int score, int fin) {
boolean go = true;
int counter = 0;
while(go) {
int dice = gen.nextInt(6) + 1;
if (dice == 1) {
System.out.println(player + " You rolled 1, your turn is over.");
System.out.println(player + " your total is " + counter);
return 0;
}
System.out.println(player + " you rolled a " + dice);
counter = counter + dice;
System.out.println(player + " Your turn score is " + counter + " Do you want to roll again? (y)es (n)o");
String ans = sc.next();
if (ans.equals("n")) {
go = false;
System.out.println(player + " your score is " + score);
return score;
}
if (score > fin) {
go = false;
System.out.println(player + " you've won the PIG DICE GAME!!");
}
}
return score;
}
private static String getName() {
System.out.println("Enter the name for a player.");
String player = sc.next();
return player;
}
}
There is a logical flaw in your program. You are calling your roll function with a score = 0 as your parameter.
int p1score = roll(p1, 0, fin);
int p2score = roll(p2, 0, fin);
while (p1score < fin && p2score < fin ) {
p1score += roll(p1, 0, fin);
p2score += roll(p2, 0, fin);
}
In your roll method, you either return 0 or you return score which is 0 everytime. So your p1score and p2score which is determinted based on what the roll function returns will both always forever be 0.
This is why your game doesn't stop because it is stuck in the while loop.
You need to change the roll function to return the score + the value that you have rolled.

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");
}
}

Loop and conditionals not working properly [duplicate]

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.");
}

Categories

Resources