How to compare variables in a loop, java - java

I have to design a program to simulate players rolling three dice for a number of rounds. Each dice throw is given points. I have to diplay for each round the dice values, and number of points for each player for those values and the winner of each round (the player with the highest points for that round, or no-one if they are the same).
I have implemented the points calculator, but I dont know how to display the winner of each round. Also, I am displaying the output vertically when it is supposed to be horizontally.
I think maybe comparing the values inside the loop in the game class may work. P.S. I am new in java, please make any suggestions to change the code if there is a better solution.
This is waht my program is displaying
round 1--> player 1: 2 4 5 points: 11
round 2--> player 1: 2 3 5 points: 10
round 3--> player 1: 2 4 6 points: 12
round 4--> player 1: 4 4 6 points: 34
round 5--> player 1: 3 4 5 points: 52
.
round 1--> player 2: 3 5 5 points: 33
round 2--> player 2: 3 6 6 points: 35
round 3--> player 2: 2 3 4 points: 49
round 4--> player 2: 1 1 3 points: 25
round 5--> player 2: 1 2 4 points: 7
This is what it is supposed to display
Round 1 Player 1: 1 3 3 points: 27 Player 2: 1 4 5 points: 10 Round winner is player 1
Round 2 Player 1: 1 2 5 points: 8 Player 2: 1 3 6 points: 10 Round winner is player 2
Round 3 Player 1: 1 4 4 points: 29 Player 2: 4 5 6 points: 55 Round winner is player 2
Round 4 Player 1: 1 3 5 points: 9 Player 2: 1 5 5 points: 31 Round winner is player 2
Round 5 Player 1: 3 6 6 points: 35 Player 2: 2 2 4 points: 28 Round winner is player 1
Total wins: Player 1: 2/ Player 2: 3
Total points: Player 1: 108/ Player 2: 134
Average points per round: Player 1: 21.6/ Player 2: 26.8
Overall points winner is player 2.
Main code
import java.util.Scanner;
public class Game {
// ------------------- FIELDS ------------------------
// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static ThreeDiceScorer thrdiesc;
public static int diceArray [];
// ------------------ METHODS ------------------------
public static void main(String[] args) {
int rounds; // input by user
int players; // input by user
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
rounds = input.nextInt();
System.out.print("\n");
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
players = input.nextInt();
System.out.print("\n");
for (int p = 0; p < players; p++) { //loop for players
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int diceArray [] = new int [3];
for (int i = 0; i < diceArray.length; i++) { // loop for random Array
diceArray [i] = 1 + (int)(6 * Math.random());
}
// Create new ThreeDice and calculator instances
thrdiesc = new ThreeDiceScorer(diceArray [0], diceArray [1], diceArray [2]);
//Calculate
thrdiesc.getDie1();
thrdiesc.getDie2();
thrdiesc.getDie3();
thrdiesc.threeSame();
thrdiesc.runOfThree();
thrdiesc.pair();
thrdiesc.allDifferent();
thrdiesc.calcTotalPoints();
thrdiesc.printResult(p,r);
}
System.out.print("\n");
}
}//end Main Method
}// end Class
ThreeDice class
public class ThreeDice {
// ---------------------- ATTRIBUTES ---------------------
protected int die1;
protected int die2;
protected int die3;
// ------------------ CONSTRUCTOR -------------------
public ThreeDice(int s1, int s2, int s3) {
// This puts the three dice values in ascending order.
int tmp;
if (s2 < s1) {
tmp = s2;
s2 = s1;
s1 = tmp;
}
if (s3 < s2) {
tmp = s3;
s3 = s2;
s2 = tmp;
}
if (s2 < s1) {
tmp = s2;
s2 = s1;
s1 = tmp;
}
die1 = s1;
die2 = s2;
die3 = s3;
}
// --------------------- METHODS ---------------------
// Accessor methods
public int getDie1() {
return die1;
}
public int getDie2() {
return die2;
}
public int getDie3() {
return die3;
}
public boolean threeSame() {
return (die1 == die3);
}
public boolean runOfThree() {
return (( (die1 + 1) == die2) && ( (die2 + 1) == die3));
}
public boolean pair() {
return (((die1 == die2) || (die2 == die3)) && (die1 != die3));
}
public boolean allDifferent() {
return (!runOfThree() && (die1 != die2) && (die2 != die3));
}
public void printResult() {
if (threeSame())
System.out.println("The roll is all the same.");
else if (runOfThree())
System.out.println("The roll is a run.");
else if (pair())
System.out.println("The roll is a pair.");
else if (allDifferent())
System.out.println("The roll is all different.");
}
}
ThreeDiceScorer (Calculator) Class
public class ThreeDiceScorer extends ThreeDice {
int total;
public ThreeDiceScorer(int s1, int s2, int s3) {
super(s1, s2, s3);
}
public void calcTotalPoints() {
int sumOfDice = die1 + die2 + die3;
if (threeSame()){
total= sumOfDice + 60;
}
else if (runOfThree()){
total= sumOfDice + 40;
}
else if (pair()){
total= sumOfDice + 20;
}
else if (allDifferent()){
total= sumOfDice;
}
}
public void printResult(int p,int r) {
System.out.println("round "+ (r+1)+ "--> " + "player "+ (p+1) + " "+ die1 + " " + die2 + " " + die3 + " " + "points: "+ total);
}
}

Sol
Switch player loop and rounds loop.
In each round loop maintain a max and update it with max value and player.
Modify printresult a little to remove round.
Loop and max:
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int max = 0;
int max_p = 0;
System.out.println("Round " + r + ": ");
for (int p = 0; p < players; p++) { //loop for players
int diceArray[] = new int[3];
//...
thrdiesc.printResult(p, r);
if (thrdiesc.total > max) {
max = thrdiesc.total;
max_p = p;
}
}
System.out.println("Winner is player " + (max_p + 1) + "\n");
}
PrintResult Method:
public void printResult(int p, int r) {
System.out.println("player " + (p + 1) + " " + die1 + " " + die2 + " " + die3 + " " + "points: " + total);
}
Misc
Indent Code properly.
Be careful while copying. (See the prompt)

While looking at your code, I have a feeling you might be able to make this much easier for yourself by creating some simple classes, five or six to be exact.
First I would break up some parts into classes. The two main classes I am thinking of are a simple Die class that is simply an immutable Die that when created sets the die value to a random number between 1 and 6. Once you create the Die object it cannot be changed. Your ThreeDice class is narrow and is really unnecessary as the three dice should really be a part of the Player object (next class) as a simple array of 3 Die objects and as an array of Die objects we can sort the dice from low to high.
A sample of a “Die” class is below:
Public final class Die implements Comparable<Die>
{
private int dieNumber;
// default constructor
public Die()
{
RollDie();
}
public int GetDieNumber()
{
return dieNumber;
}
public int compareTo(Die otherDie)
{
return this.dieNumber - otherDie.dieNumber;
}
private void RollDie()
{
dieNumber = 1 + (int)(6 * Math.random());
}
}
The next class to help would be a Player class. The important parts of this class will be a player name, then a Die object array (of size 3 in your case) to hold the players random dice. In this class you could also have methods to get the total value of the 3 dice, along with a method/variable to get the extra points the user gets if the 3 dice are the same number, if there is a pair, etc. Here we can take advantage of the sorting of the dice array from low to high when the dice array is created. This will make checking for straights easier.
A Player class example is below.
public class Player implements Comparable<Player>
{
private String playerName;
private Die[] diceArray;
private int diceTotal = 0;
private int extraPoints = 0;
private int overallTotal = 0;
private String extraPointsString = "";
public Player(String inName, Die[] inDiceArray)
{
playerName = inName;
diceArray = inDiceArray;
SetDiceTotals();
}
public String GetPlayerName()
{
return playerName;
}
public int GetExtraPoints()
{
return extraPoints;
}
public int GetDiceTotal()
{
return diceTotal;
}
public int GetOverallTotal()
{
return overallTotal;
}
public String GetExtraPointsString()
{
return extraPointsString;
}
public Die[] GetDiceArray()
{
return diceArray;
}
public String toString()
{
String playerString = playerName + " Dice values: ";
for (int i = 0; i < diceArray.length; i++)
{
if (i < (diceArray.length - 1))
playerString = playerString + diceArray[i].GetDieNumber() + ", ";
else
playerString = playerString + diceArray[i].GetDieNumber();
}
playerString = playerString + " Total: " + GetDiceTotal();
playerString = playerString + " - Special Points added: " + GetExtraPoints() + " for having " + GetExtraPointsString();
return playerString + " Total Points: " + GetOverallTotal();
}
public int compareTo(Player otherPlayer)
{
int thisTotal = this.GetDiceTotal() + this.GetExtraPoints();
int otherTotal = otherPlayer.GetDiceTotal() + otherPlayer.GetExtraPoints();
return otherTotal - thisTotal;
}
// private internal method to set dice totals, extra points and extra points string
private void SetDiceTotals()
{
int total = 0;
for (int i = 0; i < diceArray.length; i++)
{
total = total + diceArray[i].GetDieNumber();
}
diceTotal = total;
if (is3OfAKind())
{
extraPoints = 60;
extraPointsString = "Three of a Kind";
}
else
{
if (isPair())
{
extraPoints = 40;
extraPointsString = "Pair";
}
else
{
if (isStraight())
{
extraPoints = 20;
extraPointsString = "Straight";
}
else
{
extraPoints = 0;
extraPointsString = "All die are different";
}
}
}
overallTotal = extraPoints + diceTotal;
}
private boolean is3OfAKind()
{
if (diceArray[0].GetDieNumber() == diceArray[1].GetDieNumber() &&
diceArray[0].GetDieNumber() == diceArray[2].GetDieNumber())
return true;
return false;
}
private boolean isPair()
{
if (diceArray[0].GetDieNumber() == diceArray[1].GetDieNumber() ||
diceArray[0].GetDieNumber() == diceArray[2].GetDieNumber() ||
diceArray[1].GetDieNumber() == diceArray[2].GetDieNumber() )
return true;
return false;
}
// this method needs to have the diceArray sorted from low to high
private boolean isStraight()
{
if (diceArray[1].GetDieNumber() == (diceArray[0].GetDieNumber() + 1) &&
diceArray[2].GetDieNumber() == (diceArray[1].GetDieNumber() + 1) )
return true;
return false;
}
}
Then, since you want to keep totals for all the rounds, I figure you may need a Round class. This class will consist of an array of Player objects for a round. Also a round number, total points of the round from all players, an average of points for the round and a string to indicate which player won the round.
A Round class example is below.
public class Round
{
private Player[] playerArray;
private int roundNumber = 0;
private int totalPointsForRound = 0;
private double roundAveragePoints = 0;
private String roundWinnerName = "";
public Round(int inRoundNumber, Player[] inPlayerArray)
{
playerArray = inPlayerArray;
roundNumber = inRoundNumber;
totalPointsForRound = SetAllPointsForRound();
roundAveragePoints = SetAveragePoints();
roundWinnerName = SetRoundWinnerName();
}
public int GetTotalPointsForRound()
{
return totalPointsForRound;
}
public double GetAveragePointsForRound()
{
return roundAveragePoints;
}
public String GetRoundWinnerName()
{
return roundWinnerName;
}
public Player[] GetPlayerArray()
{
return playerArray;
}
public int GetRoundNumber()
{
return roundNumber;
}
private String SetRoundWinnerName()
{
// sort the array from high to low - if the first two total are equal then its a tie
Player[] tempArray = playerArray;
Arrays.sort(tempArray);
if (tempArray[0].GetOverallTotal() == tempArray[1].GetOverallTotal())
return "Tie";
if (tempArray[0].GetOverallTotal() > tempArray[1].GetOverallTotal())
return tempArray[0].GetPlayerName();
return "Unknown Winner???";
}
private double SetAveragePoints()
{
double totalPoints = GetTotalPointsForRound();
double average = totalPoints/playerArray.length;
return Math.round(average*100.0)/100.0;
}
private int SetAllPointsForRound()
{
int allPoints = 0;
for (int i = 0; i < playerArray.length; i++)
{
allPoints = allPoints + playerArray[i].GetOverallTotal();
}
return allPoints;
}
}
Then since you want to keep totals for all the players, you may want to make a small PlayerTotals class. This class will simply consist of a player name, total wins for all rounds and total points for all rounds. Keep in mind these are totals for ALL rounds not for a single round as each Player object in the Round's playerArray will contain totals for that particular round.
A PlayerTotals class example is below
public class PlayerTotals implements Comparable<PlayerTotals>
{
String playerName;
int totalWins = 0;
int totalPoints = 0;
public PlayerTotals(String inPlayerName)
{
playerName = inPlayerName;
}
public int GetTotalPoints()
{
return totalPoints;
}
public void SetTotalPoints(int inPoints)
{
totalPoints = inPoints;
}
public int GetTotalWins()
{
return totalWins;
}
public void SetTotalWins(int inWins)
{
totalWins = inWins;
}
public int compareTo(PlayerTotals otherPlayerTotals)
{
int thisTotalPoints = this.GetTotalPoints();
int otherTotalPoints = otherPlayerTotals.GetTotalPoints();
return otherTotalPoints - thisTotalPoints;
}
}
Then two more classes which you could actually combine into one class. One is a static GameUtils class that helps do some global things like: GetPlayerArray, this method gets an array of Player objects. Each Player object will contain an array of the 3 dice each player rolled. This dice array will be sorted from low to high. This is the method that gets your initial random rolls for each player for each round. Also here we can GetPlayerOverallWins where we can loop through all rounds and total up how many wins each player had. A method called GetTotalTies to get the total number of ties from all the rounds. And a method GetPlayerOverallPoints to get a total of all players points from all rounds. Also here I placed your prompts for the user to enter the number of players and number of rounds with a check to make sure the user input is valid.
A GameUtils example is below:
public final class GameUtils
{
public static Player[] GetPlayerArray(int numOfPlayers, int numOfDice)
{
Player[] playerArray = new Player[numOfPlayers];
for (int i = 0; i < numOfPlayers; i++)
{
Die[] diceArray = new Die[numOfDice];
for (int j = 0; j < numOfDice; j++)
{
diceArray[j] = new Die();
}
Arrays.sort(diceArray);
playerArray[i] = new Player("Player " + (i + 1), diceArray);
}
return playerArray;
}
public static int GetNumberOfPlayers(Scanner input)
{
return GetValidInteger("Please input number of players (greater than 0) --> ", input);
}
public static int GetNumberOfRounds(Scanner input)
{
return GetValidInteger("Please input number of rounds (greater than 0) --> ", input);
}
private static int GetValidInteger(String prompt, Scanner input)
{
boolean done = false;
int validInt = -1;
String userInput = "";
while (!done)
{
System.out.print(prompt);
userInput = input.nextLine();
try
{
validInt = Integer.parseInt(userInput);
done = true;
}
catch (NumberFormatException e)
{
System.out.println("Invalid Input: " + userInput + " Try again!");
}
}
return validInt;
}
public static int GetPlayerOverallWins(String playerName, Round[] allRounds)
{
int totalWins = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
String roundWinner = curRound.GetRoundWinnerName();
if (playerName.equals(roundWinner))
{
totalWins++;
}
}
return totalWins;
}
public static int GetTotalTies(Round[] allRounds)
{
int totalTies = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
String roundWinner = curRound.GetRoundWinnerName();
if (roundWinner.equals("Tie"))
{
totalTies++;
}
}
return totalTies;
}
public static int GetPlayerOverallPoints(String player, Round[] allRounds)
{
int totalPoints = 0;
for (int i = 0; i < allRounds.length; i++)
{
Round curRound = allRounds[i];
for (int j = 0; j < curRound.GetPlayerArray().length; j++)
{
Player curPlayer = curRound.GetPlayerArray()[j];
if (player.equals(curPlayer.GetPlayerName()))
{
totalPoints = totalPoints + curPlayer.GetOverallTotal();
break;
}
}
}
return totalPoints;
}
}
Lastly a DiceGame class with a main entry to put it all together. A dice game class will consist of global variables numberOfPlayers. numberOfRounds, numberOfDice, and a playerArray to use for each round, then an array of Rounds to hold all the rounds for totaling after all the rounds have been run. The example below starts by setting a loop for the number of rounds, in this loop we create all the players and dice values for them then save the round information into a new Round object then place each new Round object into an array. Then the results from the current round is output to the user. Once the loop on the number of rounds finishes, we should then have an array of Round objects. Here is where the PlayerTotals class helps as we can create another array of PlayerTotals objects for all rounds. This uses some methods from GameUtils and these methods could just a well be placed into this main class. After all player totals for all rounds have been added up, the results are output to the user.
Main DiceGame class example:
public class DiceGame
{
public static Scanner input = new Scanner(System.in);
static int numberOfPlayers;
static int numberOfRounds;
static int numberOfDice = 3;
static Player[] playerArray;
static Round[] allRounds;
public static void main(String[] args)
{
numberOfPlayers = GameUtils.GetNumberOfPlayers(input);
numberOfRounds = GameUtils.GetNumberOfRounds(input);
System.out.println("");
allRounds = new Round[numberOfRounds];
// for each round - we want to create players with the proper number of random dice
for (int i = 0; i < numberOfRounds; i++)
{
// get an array of players with random dice
playerArray = GameUtils.GetPlayerArray(numberOfPlayers, numberOfDice);
Round currentRound = new Round(i, playerArray);
allRounds[i] = currentRound;
// print the results of this round
System.out.println("Round " + (i + 1) + " Results - Winner is: " + currentRound.GetRoundWinnerName()
+ " -- Average score for this round: " + currentRound.GetAveragePointsForRound());
for (int j = 0; j < playerArray.length; j++)
{
System.out.println(playerArray[j].toString());
}
System.out.println("---------------------------------------");
}
// now get totals for all rounds
// first create an array of PlayerTotals
PlayerTotals[] allPlayersTotals = new PlayerTotals[numberOfPlayers];
for (int i = 0; i < numberOfPlayers; i++)
{
PlayerTotals curPlayer = new PlayerTotals(playerArray[i].GetPlayerName());
curPlayer.SetTotalPoints(GameUtils.GetPlayerOverallPoints(curPlayer.playerName, allRounds));
curPlayer.SetTotalWins(GameUtils.GetPlayerOverallWins(curPlayer.playerName, allRounds));
allPlayersTotals[i] = curPlayer;
}
// print the overall results
System.out.println("");
System.out.println(" -- Overall Results --");
System.out.println("Ties: " + GameUtils.GetTotalTies(allRounds));
Arrays.sort(allPlayersTotals);
PlayerTotals curPlayer;
for (int i = 0; i < allPlayersTotals.length; i++)
{
curPlayer = allPlayersTotals[i];
System.out.println(curPlayer.playerName + " Won " + curPlayer.totalWins + " times - Total Points: " + curPlayer.totalPoints);
}
}
}
Hope these make things easier. Good Luck!

Related

While loop not terminating when an array equals the terminate condition array. Java. First java class please be patient. Thank you

Was wondering if there was a reason that the while loop was not terminating if the arrays equal eachother, the one condition was an array set to all 2s and then when the Die array reaches all 2s I wanted the while loop to terminate. Thank you for any help.
Stuck in the mud dice game, 2 players will roll 5 dice each, and the person with the highest total wins, if one player rolls a 2
they are stuck in the mud and unable to continue rolling for the rest of the game
import java.util.*;
public class StuckInTheMud {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is player ones name?");
String firstPlayer = keyboard.nextLine();
System.out.println("What is player twos name?");
String secondPlayer = keyboard.nextLine();
Player playerOne = new Player(firstPlayer);
Player playerTwo = new Player(secondPlayer);
while (playerOne.getDice() != playerOne.endGame() || playerTwo.getDice() != playerTwo.endGame()) // this is the while loop that wont terminate
{
pressEnterKeyToContinue(firstPlayer); // these are the turns looping
playerOne.playerTurn(firstPlayer);
pressEnterKeyToContinue(secondPlayer);
playerTwo.playerTurn(secondPlayer);
}
}
public static void pressEnterKeyToContinue(String playerName) // using a continue method so the game doesn't contine on its own
{
System.out.println("\n" + playerName + ", press Enter key when you are ready to roll!");
Scanner nextTurn = new Scanner(System.in);
nextTurn.nextLine();
}
}
import java.util.*;
public class Player { // this is the player class
private int score;
private Die[] dice = new Die[6];
private String playerName;
private int roundScore;
private int totalScore;
public Player(String playerAlias) {
playerAlias = playerName;
score = 0;
for (int i = 0; i != dice.length; i++) {
dice[i] = new Die(6);
dice[i].setValue(1);
}
}
public void playerTurn(String playerName) {
roundScore = 0;
int twoRoll = 0;
System.out.print(playerName + " it is your turn, here come the dice.\n");
for (int i = 0; i != dice.length; i++) // This for loop will add random dice roll integers into the players array
{
if (dice[i].getValue() != 2) {
dice[i].roll();
if (dice[i].getValue() != 2) {
System.out.println("For roll number " + (i + 1) + " you got a " + dice[i].getValue() + "!");
roundScore(dice[i].getValue());
} else {
System.out.println("For roll number " + (i + 1) + ", you got a 2! Die " + (i + 1) + " is now stuck in the mud!");
twoRoll = 1;
}
} else {
System.out.println("Die " + (i + 1) + " is stuck in the mud since you rolled a 2, it cannot be used for the rest of the game!");
}
}
if (twoRoll == 0) {
System.out.println("\nYour total score this round was " + getRoundScore() + ".");
totalScore(roundScore);
System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
} else {
System.out.println("\nSince you rolled a 2, the score for this round is 0");
roundScore = 0;
totalScore(roundScore);
System.out.println(playerName + ", your total score for the game is " + getTotalScore() + "!");
}
}
public void roundScore(int singleRoll) {
roundScore += singleRoll;
}
public int getRoundScore() {
return roundScore;
}
public void totalScore(int roundScore) {
totalScore += roundScore;
}
public int getTotalScore() {
return totalScore;
}
public Die[] getDice() {
return dice;
}
public Die[] endGame() {
Die[] endGame = new Die[6];
for (int i = 0; i != endGame.length; i++) {
endGame[i] = new Die(6);
endGame[i].roll();
endGame[i].setValue(2);
}
return endGame;
}
}
// Die Class
// 4/21/22
// Zachary Strickler
import java.util.Random;
/**
The Die class simulates a six-sided die.
*/
public class Die // this is the die class
{
private int sides; // Number of sides
private int value; // The die's value
/**
The constructor performs an initial
roll of the die.
#param numSides The number of sides for this die.
*/
public Die(int numSides) {
sides = numSides;
roll();
}
/**
The roll method simlates the rolling of
the die.
*/
public void roll() {
// Create a Random object.
Random rand = new Random();
// Get a random value for the die.
value = rand.nextInt(sides) + 1;
}
/**
getSides method
#return The number of sides for this die.
*/
public int getSides() {
return sides;
}
/**
getValue method
#return The value of the die.
*/
public int getValue() {
return value;
}
public int setValue(int setValue) {
value = setValue;
return value;
}
}
You while loop test includes
playerTwo.getDice() != playerTwo.endGame()
By using the = operator, you are saying 'are these two arrays the same array object?'. Looking at the endGame method you can see that can never be true, you are creating a new array object every time you call that method, so could never be the same one as
playerTwo.getDice().
Instead of checking to see if they are the same object, you really want to know if they have the same values. There are some other ways of doing that. I'll give you a hint, look at java.util.Arrays package.
https://www.geeksforgeeks.org/java-util-arrays-equals-java-examples/
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
https://www.geeksforgeeks.org/compare-two-arrays-java/

Setting a value for one of my instance variables isn't working

I'm trying to write a program that essentially evaluates a 5 card poker hand that is user-generated. One part of the program is that users can choose one variable to randomly change. The issue lies with setting a value for one of my instance variables, right now, my setCards, getCards, and changeOne methods are:
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
getCards();
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
changes++;
}
In a separate class, I'm using:
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
I'm not sure why but whenever I try to use the changeOne method, keeps giving me the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 0, end 3, length 0
Which I assume is because it takes cards to be an empty string. I'm not sure what is happening and why it isn't getting the proper value of cards, help would be greatly appreciated.
Entire code:
First class:
import java.util.Scanner;
public class Assignment4{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
FiveCards myCards = new FiveCards();
int position;
String choice, cards;
char charChoice;
final char NEW = 'A';
final char CHANGE = 'B';
final char DISPLAY = 'C';
final char QUIT = 'Q';
do {
System.out.println("Choose (A: Make New Cards), (B: Change One Card), (C: Display Data), or (Q: Quit)");
choice = in.next();
charChoice = choice.toUpperCase().charAt(0);
switch(charChoice) {
case NEW:
System.out.println("*** Make New FiveCards ***");
System.out.println("Type five letters without space: ");
in.next();
cards = in.nextLine().toUpperCase();
myCards.setCards(cards);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case CHANGE:
System.out.println("*** Change One Card ***");
System.out.println("Type one position to change (0-4): ");
position = in.nextInt();
myCards.changeOne(position);
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case DISPLAY:
System.out.println("[Cards] [Score] [Changes]");
myCards.displayData();
break;
case QUIT:
System.out.println("*** End of Program ***");
break;
default:
System.out.println("Invalid input. Try Again");
break;
}
}while(charChoice!=QUIT);
}
}
Second class is:
public class FiveCards {
private String cards, history;
private int score, changes, counter;
private String allCards = "1234567890JQK";
private char randomChar;
public FiveCards() {
}
public void setCards(String str) {
this.cards = str;
calculateScore();
history = history + cards + score + changes;
changes++;
}
public String getCards() {
return this.cards;
}
public void changeOne(int pos) {
calculateScore();
history = history + cards + score + changes;
randomChar = allCards.charAt((int)(Math.random()*cards.length()));
this.cards = cards.substring(0, pos) + randomChar + cards.substring(pos + 1, cards.length());
System.out.println(cards);
changes++;
}
public void calculateScore() {
for(int i = 0; i<cards.length(); i++) {
for(int j = 0; j<cards.length(); j++) {
if((cards.charAt(i) == cards.charAt(j)) && (i != j)) {
counter++;
}
}
}
if(counter == 2) {
score = 1;
}
else if(counter == 4) {
score = 2;
}
else if(counter == 6) {
score = 3;
}
else if(counter == 8) {
score = 4;
}
else {
score = 0;
}
}
public String displayData() {
calculateScore();
history = history + cards + score + changes;
if(cards.length()<=1) {
return cards + " " + score + " " + changes;
}
else {
return "Empty" + " " + score + " " + changes;
}
}
}
First problem:
allCards.charAt(...). In the setCards you assign string to cards, but here you pick character from allCards. What is content of allCards? When it is assigned? I it assigned at all? (your code doesn't show this).
And the second problem:
Math.random()*cards.length()
Valid indexes of characters in the String are from 0 to length() - 1 inclusive, but the way you generate random index, you can give you index from 0 to length() inclusive. Change it to the Math.random()*(cards.length() - 1).

Java program to keep track of team score

Edit: I updated the below code from before and am able to get the individual quarter amounts. I'm not sure why my "teamTotal" method is not adding together all four quarters. I figured it was supposed to iterate over all of the team 1 and 2 scores and add them together to get the separate totals. However, when I run it I am only getting zero returned back to me.
public class Offical4 {
static int team1[] = new int[4];
static int team2[] = new int[4];
static int teamOneScore = 0;
static int teamTwoScore = 0;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
for (int Quarter = 1; Quarter <= 4; Quarter++) {
System.out.println("Quarter " + Quarter);
for (int qtr = 0; qtr < 4; qtr++) {
quarterScoring(team1, team2, qtr);
}
System.out.println("Q"+ (Quarter) + " score for team 1 is " + teamOneScore);
System.out.println("Q"+ (Quarter) + " score for team 2 is " + teamTwoScore);
System.out.println("\n");
}
int team1Total = teamTotal(team1);
int team2Total = teamTotal(team2);
displayGameResults(team1, team2);
System.out.println("Team one total is " + team1Total);
}
static int pointsScored;
static int teamTotal(int[] team) {
int sum = 0;
for(int i =0; i < team.length; i++)
sum += team[i];
return sum;
}
static void quarterScoring(int[] team1, int[] team2, int qtr) {
System.out.println("What team scored?(1 or 2)");
int scoreResult = keyboard.nextInt();
System.out.println("How many points did they score (1,2, or 3)");
int pointsScored = keyboard.nextInt();
if (scoreResult == 1) {
teamOneScore += pointsScored;
} else if (scoreResult == 2) {
teamTwoScore += pointsScored;
}
if (scoreResult > 2) {
System.out.println("Invalid team - quarter has ended.");
}
}
static void displayGameResults(int[] team1, int[] team2) {
System.out.println("Team 1 score is " + teamOneScore);
System.out.println("Team 2 score is " + teamTwoScore);
if(teamOneScore > teamTwoScore){
System.out.println("Team one is the winner");
}
else{
System.out.println("Team two Two wins");
}
}
}
Use the two arrays at the top of your code to keep track of the score for each team in each quarter. Then to get their totals add the values of the array up. You can use an enhanced for loop for that.
There are many way to keep track total point of each team, one idea as bellow
public class Main {
static int team1[] = new int[4]; // define here
static int team2[] = new int[4]; // define here
static int teamOneScore = 0; // define here
static int teamTwoScore = 0; // define here
static Scanner keyboard = new Scanner(System.in);
...
Then you can
System.out.println("What team scored?(1 or 2)");
int iTeam = keyboard.nextInt();
System.out.println("How many points did they score (1,2, or 3)");
int pointsScored = keyboard.nextInt();
if (iTeam == 1) {
teamOneScore += pointsScored; // Total score of Team 1
}
else if (iTeam == 2) {
teamTwoScore += pointsScored; // Total score of Team 2
}
And
System.out.println("Team 1 score is " + teamOneScore);
System.out.println("Team 2 score is " + teamTwoScore);
One more thing, I think you need to validate what input value is before do anything.

Having trouble solving logic of random number game

I am relatively new to java programming. I am currently working on building a mini guessing game, as a project to learn more Java. I am having some issues with the following:
Here are the 4 main things I am having trouble solving.
Record the answer for each user, if incorrect.
If the user was correct, skip them in subsequent rounds.
Once all players have guessed their correct number, print out the number of guesses it took for each one to guess correctly, the incorrect responses, and show a ranking of the players.
Ask if the user(s) wish to play again. If so, reset all values.
Here are the methods that I have written;
import java.io.*;
public class MultiPlayerRandomGame {
// this method asks how many users will be playing and returns the number of users
public static int howManyUsers() {
System.out.println("How many users will be playing?");
int players = IO.readInt();
return players;
}
// this method generates and returns a random number
public static int generateRandomNumber() {
int randomNumber = (int) (Math.random() * 100);
return randomNumber;
}
// this method compares user's entered guess and the generated random number then returns true/false
public static boolean compareGuess(int guess, int randomNumbers) {
boolean isGuessCorrect = false;
if (guess == randomNumbers) {
System.out.println("CORRECT!");
isGuessCorrect = true;
} else if (guess > randomNumbers) {
System.out.println("Too High");
} else if (guess < randomNumbers) {
System.out.println("Too Low");
}
System.out.println("test1");
return isGuessCorrect;
}
// this method determines whether Player N is correct or incorrect
public static boolean nextPlayer(int numOfUsers, int[] numberOfGuesses, int[] randomNumbers, int[][] numberBoard) {
for (int n = 0; n < numOfUsers; n++) {
int guessedNumber = numberOfGuesses[n];
/* if (guessedNumber == 0) {
return false;
}*/
if (numberBoard[n][guessedNumber] != randomNumbers[n]) {
return false;
}
}
return true;
}
/* this method is supposed to print out the number of guesses it took each player to guess their correct number
* CORRECTION: change the logic of this method to printing the number of guesses for one player then
* in the main method or wherever, make a for loop that prints out the number of guesses for each player
*/
public static void amountOfGuesses(int numOfUsers, int [] numberOfGuesses, int [][] numberBoard) {
int n = 0;
for ( int i = 0; i < numOfUsers; i++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[i]+ " time(s)");
}
}
// this method determines whether the user(s) would like to play again
public static boolean playAgain(String answer) {
boolean userWillPlayAgain;
if (answer.compareToIgnoreCase("no") == 0) {
userWillPlayAgain = false;
}
else {
userWillPlayAgain = true;
}
return userWillPlayAgain;
}
// this method controls the entire game
public static boolean playGame(){
boolean gameTerminate = false;
int numOfUsers = howManyUsers();
int [] randomNumbers = new int[numOfUsers];
int [] numberOfGuesses = new int [numOfUsers];
int [][] numberBoard = new int [numOfUsers][100];
// this for loop assigns the n random number(s) to the n player(s)
for (int n = 0; n < numOfUsers; n++){
randomNumbers[n] = generateRandomNumber();
System.out.println("PLAYER " + (n+1) + "'s RANDOM NUMBER: " + randomNumbers[n]);
}
do {
for (int i = 0; i < numOfUsers; i++) {
int guessedNumber = numberOfGuesses[i];
if (guessedNumber == 0 || numberBoard[i][guessedNumber-1] != randomNumbers[i]) {
System.out.println("Enter your guess Player " + (i+1) + ":");
int enteredGuess = IO.readInt();
numberBoard[i][guessedNumber] = enteredGuess;
numberOfGuesses[i] = guessedNumber + 1;
if(compareGuess(enteredGuess, randomNumbers[i])){
return true;
}
}
}
/* int n = 0;
* for ( int j = 0; j < numOfUsers; j++ ) {
n = n + 1;
System.out.println("Player " + n + " guessed " + numberOfGuesses[j]+ " time(s)"); }
*/
} while (nextPlayer(numOfUsers, numberOfGuesses, randomNumbers, numberBoard) == false);
// System.out.println("test");
return gameTerminate;
}
public static void main(String[] args){
boolean playing = true;
while (playing) {
playGame();
System.out.println("Would you like to play again?");
String answer = IO.readString();
playing = playAgain(answer);
}
System.out.println("OK, goodbye!");
}
}
Main issue as of right now: The game terminates and asks if user would like to play again after a player guesses their number, rather than after every player guesses their number.
Do I need actual Objects to make this happen and track every player or can this still be solved without objects? This is a territory I am unfamiliar with.
Right now your playGame method returns true back to main whenever any guess returns correct from compareGuess.
I would recommend setting up another array boolean[] correctGuess in playGame and mark the player number index as true if a player guesses correctly. You can use this new array to skip players who have guessed correctly, also. Once all players are marked true you can return to main.
This won't help improve your current code, but the same game can easily implemented using objects. In my opinion, the code is cleaner and easier to read.
Objects allow you to encapsulate the data required by each class. The target, number of guesses, and whether they were correct is stored in the Person object instead of in a multi-dimensional array. The values can be accessed by referencing the Person object - e.g. person.numGuesses or person.target.
By using objects, you can keep specific functionality scoped out of the main class. i.e. abstract away the implementation. In a future version of the game, you may want to change the way the target value is incremented; by using objects, the change can be made in the class which sets and checks the value - without affecting any other classes.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Game {
private final List<Person> personList = new ArrayList<>();
private Game(int numPlayers) {
for (int i = 0; i < numPlayers; i++) {
personList.add(new Person(i)); // Fill the player list
}
}
public static void main(String[] args) {
System.out.print("Enter the number of players: ");
Scanner sc = new Scanner(System.in);
int numPlayers = sc.nextInt();
// Initialise with the number of players
Game g = new Game(numPlayers);
g.mainLoop(); // Play the game
boolean playAgain = false;
do {
System.out.print("Do you wish to play again?: ");
String in = sc.next();
playAgain = "yes".equals(in);
if (playAgain) {
g.resetAll();
g.mainLoop();
}
} while (playAgain); // Only loop if they answered "yes"
}
private boolean allCorrect() {
// Check if all players have answered correctly
return personList.stream().allMatch(p -> p.correct);
}
private void resetAll() {
for (Person p : personList) {
p.reset(); // Reset each person
}
}
private void mainLoop() {
while (!allCorrect()) {
for (Person p : personList) {
p.doGuess(); // Ask for the guess
}
}
// Everyone is correct, print the scores.
for (Person p : personList) {
System.out.println("Player " + p.id + " => " + p.numGuesses + " guesses");
}
}
}
class Person {
final int id;
int numGuesses;
boolean correct;
private int target;
Person(int id) {
this.id = id;
target = new Random().nextInt(100); // Each player has a random target between 0-100
}
void doGuess() {
if (correct) {
// Skip turn if they're already correct
return;
}
numGuesses++;
System.out.print("Player " + id + " guess " + numGuesses + "(" + target + "): ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt(); // Read the guess
if (i == target) {
correct = true;
System.out.println("Correct!");
}
}
void reset() {
target = new Random().nextInt(100); // New target between 0-100
numGuesses = 0; // Reset the counter
correct = false;
}
}

problems with dice game

whenever the code goes through the compiler it prints out the same number an infinite amount of times, i need it to compile random numbers several times. I tried to use the while loop to print out more times. However it just prints out the same number. The purpose of the game is for two players (and AI and one person), to compete to first reach 100 points, whenever a player gets two 1's the points will reset.
class piggame {
public static void main(String[] args) {
Dice d1 = new Dice();
d1.rolls();
int dave = d1.rolls();
Dice d2 = new Dice();
d2.rolls();
int joe = d2.rolls();
Dice d3 = new Dice();
d3.rolls();
int kurt = d1.rolls() + d2.rolls();
int sum1 = d1.rolls() + d2.rolls();
sum1 += d1.rolls() + d2.rolls();
while (dave != 1 && joe != 1){
System.out.println("you have rolled " + kurt);
}
}
}
class Dice {
public int rolls() {
Random r = new Random();
return r.nextInt(6) +1;
}
}
You should call rolls() inside loop. At snippet you pasted rolls are made once before the loop and then inside it you just printing this one roll result (which indeed will be infinite loop OR won't execute in case of rolls being ones right away, as rolls are never made again when you inside this while).
This code is not perfect, but it should solve your problem.
public static void main(String[] args) {
int dave = 0;
int joe = 0;
int kurt = 0;
while (dave != 1 && joe != 1){
Dice d1 = new Dice();
d1.rolls();
dave = d1.rolls();
Dice d2 = new Dice();
d2.rolls();
joe = d2.rolls();
Dice d3 = new Dice();
d3.rolls();
kurt = d1.rolls() + d2.rolls();
int sum1 = d1.rolls() + d2.rolls();
sum1 += d1.rolls() + d2.rolls();
System.out.println("you have rolled " + kurt);
}
}
import java.util.Random;
class PigGame
{
public static void main(String[] args)
{
int dave = 0;
int joe = 0;
int kurt = 0;
int roll_count = 0;
while (dave != 1 && joe != 1)
{
System.out.println("-----------------------------------------------");
System.out.println("Roll number: " + roll_count++);
System.out.println("-----------------------------------------------");
dave = new Dice().roll();
joe = new Dice().roll();
kurt = new Dice().roll();
System.out.println("Dave rolled: " + dave);
System.out.println("Joe rolled: " + joe);
System.out.println("Kurt rolled: " + kurt);
System.out.println("");
}
}
}
class Dice {
public int roll() { return new Random().nextInt(6) + 1; }
}
I don't think you're providing a solution to the given requirement:
Two players (but you have included three players - Joe, Dave and Kurt).
If a player rolls two consecutive ones, that player's score is reset (e.g. if player Dave rolls a one and then rolls another one on his next turn, his score is reset to 0).
In my previous answer, I was only trying to tidy up your code. I wasn't looking at the actual requirement.
You haven't mentioned if a player gets a single point per roll of the dice, or if the value of what they roll is added to their score. I'm going to assume it's the latter.
You should include another class called "Player". The Player class would contain variables to store what the current roll was, what the previous roll was, and the player's current score. It should also include methods to roll the dice, check if the player has reached a score of 100, check if a player has rolled two consecutive ones.
Here's a very simple implementation (that will tell you which player wins at the end, and how many points the winner has won by):
import java.util.Random;
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class PigGame
{
public static void main(String[] args)
{
Player player1 = new Player("Dave");
Player player2 = new Player("Joe");
int roll_count = 0;
while (!player1.reachedFinishingScore() && !player2.reachedFinishingScore())
{
int p1_roll = player1.roll();
int p2_roll = player2.roll();
System.out.println("-----------------------------------------------------");
System.out.println("Roll number: " + roll_count++);
System.out.println("-----------------------------------------------------");
System.out.println(player1.get_name() + " rolled: " + p1_roll + ". Total Score: " + player1.get_score());
System.out.println(player2.get_name() + " rolled: " + p2_roll + ". Total Score: " + player2.get_score());
System.out.println("");
}
if (player1.get_score() == player2.get_score())
System.out.println("It was a draw!");
else if (player1.get_score() > player2.get_score())
System.out.println(player1.get_name() + " wins by " + (player1.get_score() - player2.get_score()) + " points!");
else
System.out.println(player2.get_name() + " wins by " + (player2.get_score() - player1.get_score()) + " points!");
System.out.println("");
}
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Dice {
public int roll() { return new Random().nextInt(6) + 1; }
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Player
{
private String name; // Player's name.
private int prev_roll = 0; // Value of Player's previous roll.
private int curr_roll = 0; // Value of Player's current roll.
private int score = 0; // The Player's score.
public Player(String name) { this.name = name; }
public int roll()
{
int curr_roll = new Dice().roll();
this.prev_roll = this.curr_roll; // Make previous roll value of last current roll.
this.curr_roll = curr_roll; // Set value of current roll to what was just rolled.
this.score += curr_roll;
if (rolledTwoOnes()) this.score = 0;
return curr_roll;
}
private boolean rolledTwoOnes() { return (this.prev_roll == 1 && this.curr_roll == 1); }
public boolean reachedFinishingScore() { return this.score >= 100; }
public int get_score() { return score; }
public String get_name() { return this.name; }
}
The above implementation could be improved by not "hard-coding" player1 and player2. Instead, you could use an array of players, which would make it easier to not limit the number of players (i.e. you could have 100 players).
Okay, last one (I promise):
import java.util.Random;
import java.util.Arrays;
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Config
{
public static final int NUM_OF_PLAYERS = 10;
public static final int NUM_OF_DICE_FACES = 6;
public static final int WINNING_SCORE = 100;
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class PigGame
{
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void create_players(Player[] p, int num_players)
{
for (int i = 0; i < num_players; i++)
p[i] = new Player("Player " + String.format("%02d", i + 1));
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void all_players_roll_dice(Player[] p)
{
for (int i = 0; i < p.length; i++)
p[i].roll();
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static boolean no_winners(Player[] p)
{
int i = 0;
boolean bWinner = false;
while (i < p.length && (bWinner = !p[i].reachedFinishingScore()))
i++;
return bWinner;
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void display_roll_details(Player[] p, int current_roll)
{
System.out.println("\n--------------------------------------------------------");
System.out.println("CURRENT ROLL: " + (current_roll + 1));
System.out.println("--------------------------------------------------------");
for (int i = 0; i < p.length; i++)
System.out.println(p[i].get_name() + " rolled: " + p[i].get_roll() +
". Score: " + p[i].get_score());
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void display_final_scores(Player[] p, int roll_count)
{
System.out.println("\n\n**********************************************************");
System.out.println("FINAL SCORES AFTER " + roll_count + " ROLLS (HIGHEST TO LOWEST):");
System.out.println("**********************************************************\n");
for (int i = 0; i < p.length; i++)
{
Arrays.sort(p);
System.out.println(p[i].get_name() + " scored: " + p[i].get_score());
}
System.out.println("\n\nDon't be a player hater!\n\n");
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
public static void main(String[] args)
{
Player[] players = new Player[Config.NUM_OF_PLAYERS];
create_players(players, Config.NUM_OF_PLAYERS);
int roll_count = 0;
while (no_winners(players))
{
all_players_roll_dice(players);
display_roll_details(players, roll_count++);
}
display_final_scores(players, roll_count);
}
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Dice {
public int roll() { return new Random().nextInt(Config.NUM_OF_DICE_FACES) + 1; }
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
class Player implements Comparable<Player>
{
private String name; // Player's name.
private int prev_roll = 0; // Value of Player's previous roll.
private int curr_roll = 0; // Value of Player's current roll.
private int score = 0; // The Player's score.
public Player(String name) { this.name = name; }
public int roll()
{
int curr_roll = new Dice().roll();
this.prev_roll = this.curr_roll; // Make previous roll value of last current roll.
this.curr_roll = curr_roll; // Set value of current roll to what was just rolled.
this.score += curr_roll;
if (rolledTwoOnes()) this.score = 0;
return curr_roll;
}
private boolean rolledTwoOnes() { return (this.prev_roll == 1 && this.curr_roll == 1); }
public boolean reachedFinishingScore() { return this.score >= Config.WINNING_SCORE; }
public int get_score() { return this.score; }
public int get_roll() { return this.curr_roll; }
public String get_name() { return this.name; }
// For sorting the array (from highest scores to lowest).
#Override
public int compareTo(Player p)
{
return ((Integer)p.get_score()).compareTo(((Integer)get_score()));
}
}
Using the above, you can easily alter the number of players, number of dice faces, and the score that needs to be reached for a win.

Categories