Why doesnt the colonySize variable change? - java

In this program, there is a 20% chance the amoeba colony will get sick if it has vitamins, and 25% it will get sick if it does not. Does the getSick() method represent this correctly?
Also, no matter how many times I run the program, the colony never gets sick, and none of them die. which I find very peculiar. What do you suggest I change? Thanks for your help.
public class AmoebaColony {
//instance variables
private String name;
private String caretakerName;
private long colonySize;
private boolean isVitamin;
private int successfulBreeds = 0;
private boolean sickness;
//AmoebaColony constructor
public AmoebaColony(String name, String caretakerName, long colonySize,
boolean isVitamin) {
this.name = name;
this.caretakerName = caretakerName;
this.colonySize = colonySize;
this.isVitamin = isVitamin;
}
public void feed()
{
colonySize *= 2;
successfulBreeds++;
}
public void getSick()
{
Random n = new Random();
if (isVitamin)
{
int c1 = n.nextInt(19);
if (c1 == 0)
{ sickness = true; }
else
{ sickness = false; }
}
else if (isVitamin == false)
{
int c2 = n.nextInt(24);
if (c2 == 0)
{ sickness = true; }
else
{ sickness = false; }
}
}
public String isSick()
{
if (sickness == true)
{
return "did";
}
else
{
return " did not ";
}
}
public void die() {
if (sickness == true)
{
colonySize = colonySize - (colonySize/10);
}
else if (sickness == false)
colonySize = colonySize;
}
//returns how many times it successfully bred
public int getSuccess()
{
return successfulBreeds;
}
//returns size of colony
public long getSize()
{
return colonySize;
}
}
public class AmoebaColonyTester {
public static void main(String[] args) {
//Get variables
String name = JOptionPane.showInputDialog(null, "What will be the name of the colony?");
String caretakerName = JOptionPane.showInputDialog(null, "What is the name of the caretaker of the colony?");
long colonySize = Integer.parseInt(JOptionPane.showInputDialog(null, "Welcome, " + caretakerName + "! What is the starting size of the colony?"));
int feedTimes = Integer.parseInt(JOptionPane.showInputDialog(null, "How many times do you want to feed the colony?"));
int breedTimes = Integer.parseInt(JOptionPane.showInputDialog(null, "How many times do you want your colony to breed?"));
int vitamin = JOptionPane.showConfirmDialog(null,"Do you want to give vitamins to your colony?", "Please select",
JOptionPane.YES_NO_OPTION);
boolean isVitamin;
if (vitamin == 1)
isVitamin = true;
else
isVitamin = false;
int feedCounter = 0;
//create colony object
AmoebaColony amoeba = new AmoebaColony(name, caretakerName, colonySize, isVitamin);
//feed the colony so it can breed
for(int x = 1; x <= feedTimes; x++)
{
if (x <= breedTimes)
{
amoeba.feed();
feedCounter++;
}
}
//get maximum colony size
long finalColony = amoeba.getSize();
;
//amoeba get sick :/
amoeba.getSick();
amoeba.die();
System.out.println(amoeba.getSize());
//display info on the screen
JOptionPane.showMessageDialog(null, "The colony name is " + name + "\nThe caretaker name is " + caretakerName +
"\nThe starting colony size was " + colonySize + "\nThey were fed " + feedCounter
+ " times \nRequested number of times to breed: " + breedTimes
+ " \nThey successfully bred " + amoeba.getSuccess() + " times\nThe colony " + amoeba.isSick() +
" get sick and "+ (finalColony - amoeba.getSize()) + " died \n"
+ " The final size of the colony is " + amoeba.getSize());
}
}

A 20% chance of something means that 1 out of 5 times it is supposed to be true. But you actually calculate the sickness as 1 in 19 times (nextInt(19) gives you the numbers between 0 and 18 inclusive, randomly).
So for 20% you need to use n.getInt(5) and for 25% chance you need to use n.getInt(4).
Other than that, just run it enough times. I don't suppose you ran it enough times for a 1 in 19 chance, given that your program runs you through several dialogs every time you run it. But I ran it and got several "did".

Related

Store array at runtime

I am an absolute beginner in programming and am facing my first big tasks.
The task is a warehouse management. All newly entered boxes should be stored in an array at runtime.
The problem is that I can create a new chest, but it will be overwritten or not saved.
My idea is that I call the run function every time an entry was successful.
import java.util.Arrays;
public class lager {
static int parser (String value) {
if (value == null) {
return -1;
} else {
return Integer.parseInt(value);
}
}
static void run (int[][]chests, int chestAmount, int maxStorage) {
//Fallunterscheidung
String option = JOptionPane.showInputDialog("What do you want to do (Type: 1-5)? \n" +
"\n" +
" 1 - Create chest \n" +
" 2 - Delete chest \n" +
" 3 - Change chest \n" +
" 4 - Show chest \n" +
" 5 - Show all");
System.out.println(chestAmount);
int optionParsed = parser(option);
if (optionParsed > 5){
System.out.println("Input incorrect or process aborted!");
run(chests, chestAmount, maxStorage);
} else if (optionParsed < 1){
System.out.println("Input incorrect or process aborted!");
return;
} else {
if (optionParsed == 1){
boolean response = create(chests, chestAmount, maxStorage);
if (!response){
System.out.println("Input incorrect or process aborted!");
} else {
System.out.println("Process successfully completed!");
}
} else if (optionParsed == 2){
boolean response = delete(chests, chestAmount, maxStorage);
if (response){
System.out.println("Input incorrect or process aborted!");
} else {
System.out.println("Process successfully completed!");
}
}
}
run(chests, chestAmount, maxStorage);
}
static boolean create (int[][]chests, int chestAmount, int maxStorage){
if (chestAmount > maxStorage - 1) {
System.out.println("The storage is already full!");
return false;
} else {
int length = Integer.parseInt(JOptionPane.showInputDialog("How long is the chest in centimeters? (e.g. 115)"));
int width = Integer.parseInt(JOptionPane.showInputDialog("How wide is the chest in centimeters? (e.g. 115)"));
int height = Integer.parseInt(JOptionPane.showInputDialog("How high is the chest in centimeters? (e.g. 115)"));
//THIS IS PROBABLY WHERE THE ERROR OCCURS
chests[chestAmount] = new int[]{length, width, height};
chestAmount++; //Count up help variable
System.out.println(chestAmount);
System.out.println("Stock " + chestAmount + " / " + maxStorage);
System.out.println(Arrays.toString(chests[chestAmount - 1]));
return true;
}
}
static boolean delete (int[][]chests, int chestAmount, int maxStorage){
String removeChest = JOptionPane.showInputDialog("Which chest do you want to delete? 1 - " + chestAmount);
int removeChestParsed = parser(removeChest);
if (removeChestParsed > chestAmount || removeChestParsed < 1){
System.out.println("Chest not available.");
return false;
} else {
chestAmount--;
chests[removeChestParsed - 1] = chests[chestAmount];
chests[chestAmount] = null;
return true;
}
}
public static void main(String[] args) {
int maxStorage = 75;
int[][] chests = new int[maxStorage][3]; //TODO: Wert 75 dynamisch anpassbar -- Fertig
//Hilfsvariable
int chestAmount = 0;
run(chests, chestAmount, maxStorage);
}
}
The problem was fixed. After I defined the variable chestAmount in the class Lager and not in the main method, everything went as desired.

Creating an array of objects but it doesn't find the symbols

I am creating an array of Players in a minigame in Java. There is a class called Players and one called Game.
In the Main we scan two names and send them to the Game
game.createPlayer(name1, name2);
and later on try to get some information back
playerArray[(game.getPlayerTurn() % 2)].getPlayerName();
The Player gets constructed in the Game as an array:
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
Player[] playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
with the Player as a standard class:
public class Player
{
private String playerName;
public Player( String playerName )
{
this.playerName = playerName;
}
public String getPlayerName()
{
return playerName;
}
}
This however returns multiple errors saying it cannot find the symbol wherever i try to find out the name of the player. Did I not properly instanciate them?
Additional code (as per request):
package oop.nimspiel;
import java.util.Scanner;
import java.util.Arrays;
public class Game
{
private int take;
private int turn;
private int playerTake;
private int playerTurn;
protected Player[] playerArray;
public Game(int turn, int playerTurn)
{
this.turn = turn;
this.playerTurn = playerTurn;
}
protected void setPlayerTake(int take)
{
this.playerTake = take;
}
public int getPlayerTake()
{
return playerTake;
}
public void incrementTurns()
{
turn = turn + 1;
playerTurn = playerTurn + 1;
}
public int getTurn()
{
return turn;
}
public int getPlayerTurn()
{
return playerTurn;
}
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}
public String getPlayer()
{
String playerName = playerArray[(getPlayerTurn() % 2)].getPlayerName();
return playerName;
}
public void checkTake(int take)
{
Scanner input = new Scanner(System.in);
this.take = take;
boolean rightInput = false;
do {
if (take < 1 || take > 3)
{
System.out.println("Your input was wrong, please use a number between 1 and 3.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else if (stoneheap.getStones() < take) {
System.out.println("There are only " + stoneheap.getStones() + " stones left.");
System.out.println("Please take less.");
System.out.println("How many stones would you like to take?");
take = input.nextInt();
rightInput = false;
}
else
{
rightInput = true;
}
} while (rightInput == false);
}
}
and the Main:
package oop.nimspiel;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Main
{
private int take;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String nextRound;
do
{
int maxPlayers = 2;
int startTurn = 1;
Game game = new Game ( startTurn, (1 + (int)(Math.random() * ((maxPlayers - 1) + 1)) ) );
int minStones = 20;
int maxStones = 30;
Stoneheap stoneheap = new Stoneheap((minStones + (int)(Math.random() * ((maxStones - minStones) + 1)) ) );
System.out.println("Rules: Two players take stones from a heap of 20 to 30 until there are no more left. The one to take the last stone loses. Each round you can only take between 1 - 3 stones. Have fun!"); // Rules
System.out.println("");
System.out.println("Hello Player 1, what is your name?");
String name1 = input.next();
System.out.println("");
System.out.println("Hello Player 2, what is your name?");
String name2 = input.next();
game.createPlayer(name1, name2);
System.out.println("");
System.out.println("Number of stones: " + stoneheap.getStones());
System.out.println("The first to draw is Player " + game.getPlayerTurn());
System.out.println("The game starts now!");
while (stoneheap.getStones() > 0)
{
if ((game.getPlayerTurn() % 2) > 0) // Turn Player 1
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
else // Turn Player 2
{
System.out.println("It is your turn " + playerArray[(game.getPlayerTurn() % 2)].getPlayerName() + ".");
System.out.println("How many stones would you like to take?");
int take = input.nextInt();
game.checkTake(take);
game.setPlayerTake(take);
stoneheap.currentStones();
System.out.println("There are " + stoneheap.getStones() + " stones left.");
}
game.incrementTurns();
}
System.out.println("The game has ended and the winner is ...");
System.out.println(playerArray[(game.getPlayerTurn() % 2)].getPlayerName());
System.out.println("It took " + (game.getTurn() - 1) + " turns." );
System.out.println("");
System.out.println("Do you want to play another round? Y for yes, anything else for no");
String userInput = input.next();
nextRound = userInput.toUpperCase();
} while (nextRound.equals("Y"));
}
}
In your createPlayer method, you should access playerArray by this keyword (this.playerArray = new Player[2]).
Currently you are creating an array on the fly, and the class variable is untouched, that's why you are getting an exception.
public class Game
{
private Player[] playerArray;
[...]
public void createPlayer(String name1, String name2)
{
this.playerArray = new Player[2];
playerArray[0] = new Player(name2);
playerArray[1] = new Player(name1);
}

How to print out information from data used in arrays?

My code asks for a user to enter how many wins, losses, and ties 6 different sports teams have gotten throughout a season. How can I make it so that once all the information has been received, it will print out how many wins, ties, and losses each team have gotten, as well as displaying the total amount of each?
Code:
package SMKTeamStandings;
import java.util.Scanner;
public class SMKTeamStandings {
public static Scanner in = new Scanner(System.in);
public static int number(int max, int min) {
int teamchoice = 0;
for (boolean valid = false; valid == false;) {
teamchoice = in.nextInt();
if (teamchoice >= min && teamchoice <= max) {
valid = true;
} else {
System.out.println("Please enter a different value.");
}
}
return teamchoice;
}
public static boolean finished(boolean[] completedArray) {
int i = 0;
boolean done;
for (done = true; done == true;) {
if (completedArray[i++] == false) {
done = false;
}
}
return done;
}
public static void main(String[] args) {
int teamChoice = 0, gamesNum;
String[] sportteams = {"Basketball", "Football",
"Hockey", "Rugby",
"Soccer", "Volleyball"};
boolean[] completed = new boolean[sportteams.length];
int[][] Outcome = new int[64][sportteams.length];
for (boolean done = false; done == false;) {
for (int i = 0; i < sportteams.length; i++) {
System.out.print(i + 1 + " - " + sportteams[i]);
if (completed[i] == true) {
System.out.println(" - Finished");
} else {
System.out.println();
}
}
System.out.print("\nChoose a team from the list above:");
teamChoice = number(6, 1);
teamChoice--;
System.out.print("\nHow many games total did the " + sportteams[teamChoice]
+ " team play this season?: ");
gamesNum = in.nextInt();
System.out.format("\n %10s %10s %10s %10s %10s \n\n", "", "Possible Outcomes:",
"1 - Win",
"2 - Tie",
"3 - Loss");
for (int wintieloss = 0; wintieloss < gamesNum; wintieloss++) {
System.out.print("\nEnter the outcome for game "
+ (wintieloss + 1) + ": ");
Outcome[wintieloss][teamChoice] = number(3, 1);
}
System.out.println("\n");
completed[teamChoice] = true;
done = finished(completed);
If I understood you correctly, you just want to output the data you got from the user. To do that you could go through the data array using a for loop and accessing the data using indices.
for(int team = 0; team < sportteams.length; team++) { // for each team
System.out.println((team + 1) + " - " + sportteams[team]); // output the team
int game = 0; // index of the current game
while(Outcome[game][team] != 0) { // while there is data
System.out.print("Game " + (game + 1) ": " + Outcome[game][team] + " "); // print the data
game++; // increment the index
}
System.out.println("Total games: " + game); // print the last index == total number of games
System.out.println();
}

How to compare variables in a loop, 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!

How to pass information with a get properly in java

I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `
If you have a funftion in the class, that exhibits the var, then it should be fine. You need to make PressureInput a object, with PressureInput varnamePI = new PressureInput();
Then, access the var through varnamePI.sysAvrg=0; or so...

Categories