How to make a counter persist in Java? - java

I'm making a dice game that scores points based on rolling a 7 or 11(pair of dice). The game keep track of the bets and score. The current score should be added to 3 times the bet amount if the the condition is met. However the score only changes the in the first instance the condition is met, then remain the same through any other roll attempts. I tried to set my getters and setters to be static but that didn't work. What can I do to make my counter work properly?
Program:
public Game() {
final Dice throwDice = new Dice();
//Roll Dice
rollDice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
throwDice.PairOfDice();
diceResult.setText("You rolled: " + throwDice.getDie1() +
" + " + throwDice.getDie2() +
" = " + throwDice.getTotal());
currentScore.setText("Score: $" + throwDice.getScore());
if(throwDice.getTotal() == 7 || throwDice.getTotal() == 11) {
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
currentScore.setText("Score: $" + throwDice.getScore());
}
}
});

The declaration of your Dice:
Dice throwDice = new Dice();
is in actionPerformed() which means it is created every time you call that function.
Move the declaration into Game, ie. make it an attribute of a game and you should be fine.
You can safely make Dice::score, Dice::getScore() and Dice:setScore(int) non-static.
UPDATE: Given there is still an issue, perhaps try replacing:
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
with:
throwDice.setScore(throwDice.getScore() + (3 + throwDice.getBet()));

In your question you say:
The current score should be added to 3 times the bet amount
You are not adding to the current score. You are only setting the score to the 3 times the bet amount every time. So the value will not change (unless, of course, you change the bet amount).
throwDice.setScore(Integer.parseInt(input.getText()) * 3)
Instead you need to add it to the current score:
throwDice.setScore(throwDice.getScore() + Integer.parseInt(input.getText()) * 3)

You need to move
Dice throwdice = new Dice`
up the code so that it is not called every time it enters actionperformed

Related

Run each loop at a different time interval

I'm currently working on a program that pits two simulated fighters against one another. The way I have it right now, each round is done and the output is printed all at once (virtually all at once because it is calculated so fast).
How would I take the below code and make it so that actions in the second loop occur in pseudo real time where it executes x amount of seconds where x is a random roll? Any suggestions or guidance would be great. I would even settle for the second while loop executing every three seconds or so. This is a prototype for now and the simulation will get more varied so reading the output may get more interesting.
public static void fight(Character player1, Character player2, int roundMax){
player1.setTempHitPoints(player1.getHitPoints());
player2.setTempHitPoints(player2.getHitPoints());
int r = ROUND;
while(!isFightOver(player1, player2)){
roundTimer = 0;
System.out.println("================");
System.out.println("Round " + r + " FIGHT!");
System.out.println("================");
while(roundTimer < roundMax && !isFightOver(player1, player2)){
roundTimer = roundTimer + Commands.roll(10);
round(player1, player2);
timerPrint(roundTimer, roundMax);
}
System.out.println("================");
System.out.println("Round " + r + " OVER!");
System.out.println("================");
System.out.println("");
if(!isFightOver(player1, player2)){
Commands.rest(player1);
Commands.rest(player2);
}
System.out.println("");
r++;
}
declareWinner(player1, player2);
}
You can use Thread.sleep() to slow down the processing.
E.g. Thread.sleep(1000) causes the current thread to suspend execution for a second (1000 ms). Can you use that method judiciously to put delays into the code? You can use java.util.Random to generate random numbers.
Random random = new Random();
Thread.sleep((random.nextInt(6) + 1) * 1000); // Delays from 1 - 6 secs

java programming with this class

Hey I'm writing a java class and the result has to be from this image
.
The whole program works great but in the end i don't get the correct math output. I think it some problem in my equation. Can someone help me with the problem. Thank you
import java.util.Scanner;
import java.awt.Toolkit;
public class Sports
{
public static void main(String[] args)
{
//create scanner object
Scanner input=new Scanner(System.in);
//create tolkit object
Toolkit tk=Toolkit.getDefaultToolkit();
int players;
int team=15;
System.out.println("SporT's Team Calculator");
System.out.println("=======================");
System.out.println("Enter the Total number of players===>");
players=input.nextInt();
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
players=input.nextInt();
while(players>15 || players<9 )
{
tk.beep();
System.out.println("\nInvalid number of players per team, please re-enter...");
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
players=input.nextInt();
players=players%team;
}
System.out.println("There will be " + players + " teams, "
+ "with " + players + " players " + "left over.");
System.out.println("\nThank you for using SporT's Software!");
}
}
You are saving both the total number of players and the number of players on a team into the same variable players. If you were to answer that the total number of players is 142 it'll immediately be overwritten by the next assignment to players for the number per team. These should be separate variables int playersPerTeam for instance
First, you are working with java so the variable
players
will constantly gets overridden.
To solve this, divide the variable
players
into 2 different variables, one to count the number of players(total) and another to count the number of players per team. This also means that you will need to change the part when you continuously ask the user for a valid input set (in the while loop) .
Secondly, your math in calculating your total number of teams and the players left over are incorrect. Below, I included a working version:
int numTeams = totalPlayers / playersPerTeam;
int playersLeft = totalPlayers - (playersPerTeam * numTeams);
System.out.println("There will be " + numTeams + " teams, " + "with " + playersLeft + " players " + "left over.");
It seems like you are retrieving two pieces of information: the total number of players and the players per team. So you will need two variables to store both pieces of information. Instead of overriding the same variable - losing the first piece of information collected.
The Equations:
To get the number of teams:
(int)(players / playerPerTeam)
To get the number of left over players:
players-playerPerTeam*totalTeams
Also I don't understand why you are getting two different numbers, 11 and 10, for the same variable, players in the console.
i actually already figured it out but thanks.
import java.util.Scanner;
import java.awt.Toolkit;
public class Sports
{
public static void main(String[] args)
{
//create scanner object
Scanner input=new Scanner(System.in);
//create tolkit object
Toolkit tk=Toolkit.getDefaultToolkit();
int players;
int team;
System.out.println("SporT's Team Calculator");
System.out.println("=======================");
System.out.println("Enter the Total number of players===>");
players=input.nextInt();
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
team=input.nextInt();
while(team>15 || team<9 )
{
tk.beep();
System.out.println("\nInvalid number of players per team, please re-enter...");
System.out.println("Enter the Number of players per team" +
"\n(at least 9 & no more than 15 per team)===>");
team=input.nextInt();
}
int result=players/team;
int player= players%team;
System.out.println("There will be " + result + " teams, "
+ "with " + player + " players" + " left over.");
System.out.println("\nThank you for using SporT's Software!");
}
}

Differentiating variable between superclass and subclasses [duplicate]

This question already has answers here:
Java Static vs Instance
(9 answers)
Closed 7 years ago.
I'm working on a program that allows a user to choose a home and away football team between four teams. I created a generic superclass team that defines the points assigned per safety/field goal/touchdown. A random number is generated and then based on that number the program steps through a conditional if/else statement to determine action and points.
This is in the SuperClass:
public void possessionPoints()
{
if(points<lowNopoints){
score = noPoints;
totalScore = totalScore + score;
System.out.println("No points, plus " + score);
}
else if(points<lowSafetypoint){
score = safetyPoint;
totalScore = totalScore + score;
System.out.println("Safety, plus" + score);
}
else if(points<lowFieldgoal){
score = fieldGoal;
totalScore = totalScore + fieldGoal;
System.out.println("Field goal, plus" + score);
}
else{
score = touchDown;
totalScore = totalScore + touchDown;
System.out.println("Touchdown, plus" + score);
}
ArrayList<Integer> totalScore;
totalScore = new ArrayList<>();
totalScore.add(score);
//the sum score
int sum = totalScore.stream().mapToInt(Integer::intValue).sum();
System.out.println("Current score is: " + sum);
}
Note: above totalScore is intialized as public static int totalScore = 0;
Throughout it all, I want to keep track of totalScore. I have this setup in my superclass, however, when the program is run it adds up the score through the entire game and does not differentiate between teams.
Output:
Home team action.
No points, plus 0
Current score: 0
Away team action.
Field goal, plus3
Current score: 3
Home team action.
Field goal, plus3
Current score: 6
Away team action.
Field goal, plus3
Current score: 9
Home team action.
Safety, plus2
Current score: 11
Also, if it helps, this is all that I set in the each subclass for the other teams below. I do not do anything with totalScore.
public class PackersSub extends GenericSuper{
public PackersSub()
{
lowNopoints = 4;
lowSafetypoint = 5;
lowFieldgoal = 7;
}
Any ideas on how to fix this issue? I want to keep track of totalScore per team. Thank you!
If you want to keep track at per-team level, then you should define it as member variable, so that each team will have it own copy of totalScore field.
Having a static filed in the super class means that it will always be a total aggregation of all the action which is happening in the sub-classes. Because only one copy of static fields is maintained per-class. In your case you have defined it in the super-class, which makes it a global field for score aggregation.

Trying to compare rep sales in an array list in Java

Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}

Variable Values in Java

I have a quick question in regards to the value of how variable values work. I am working on a program right now, which looks like this:
public void run() {
println("There are " + ATOMS + " initially.");
int atoms = ATOMS;
int year = 0;
while (atoms > 0) {
for (int i = atoms; i > 0; i--) {
println(i);
if( rgen.nextBoolean() ) {
atoms--;
println("The total atoms is " + atoms);
}
println("The total for i is " + i + "\n" );
}
year++;
println("There are " + atoms + " at the end of year " + year );
}
}
At the part with the for loop, and setting the variable i to the value of atoms, is what has me confused. Lets say the value of atoms starts at 20. It goes through the for loop and lets assume that the first time through the RandomGenerator makes it true. So that subtracts 1 from atoms. Then after that the value of i should also be minused due to the i--. So my question is: When I set the variable i to the value of atoms does that just take i and set it to the initial value of 20? And then from there every time I adjust the value of i it is taking off of its own version of 20, and then when I change the value of atoms it, too has its own value. So when I subtract from atoms, that is not also being subtracted from i? That is the only way I can make sense of it because this program is written and works correctly, but that part has me confused.
Thank you very much in advance for any help!
yes you have answered your own question. the variable i and atoms are two separate instances.
when you start the loop you are setting i equal to the same value as atoms but they are still separate variables. therefore inside the loop when you change the value of one it does not affect the other.
Once you set the value of i=atoms, it no longer changes. It is the loop initializer, and will no longer be processed.
"i" of course will be decremented continuously (because of the i-- decrement).
But you can change the value of atoms to whatever and the results will not change.
i=atoms is the initialization in the for loop. So then on, value of i independent of atoms.

Categories

Resources