Differentiating variable between superclass and subclasses [duplicate] - java

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.

Related

How can I fix this java?

I am working on this program with these instructions:
Bus Passengers: Write a program that is to be used to count how many passengers are travelling on
buses that pass a particular bus stop in a given hour. It should use a while loop to repeatedly ask the user to give the number of passengers on the bus that just passed. It should stop when the special code X is entered as the number of passengers. It should then give the number of buses and the total number of passengers counted in that hour. For example, one run might be as follows.
How many passengers were on the bus? 2
How many passengers were on the bus? 5
How many passengers were on the bus? 10
How many passengers were on the bus? 3
How many passengers were on the bus? 12
How many passengers were on the bus? 1
How many passengers were on the bus? 0
How many passengers were on the bus? X
There were a total of 33 passengers on 7 buses.
I am trying to fix an error:
Few points to note:-
You don't need System.exit()
In java variables are only accessible inside their scope i.e. the region they are created in.
I tried to rewrite code as following:-
import java.util.Scanner;
public class Bus {
int busCount =0;
int passengerCount =0;
Scanner scanner= new Scanner(System.in);
public static void main(String args[]){
Bus bus = new Bus();
bus.getResults();
}
private void addBusAndPassenger(String input){
try{
int a = Integer.parseInt(input);
busCount = busCount + 1;
passengerCount = passengerCount + a;
}catch(NumberFormatException e){
System.out.println("Please provide integer or X as input");
}
}
private void getResults(){
String a =null;
while (!("X".equals(a))){
System.out.print("How many passengers were on the bus? ");
a = scanner.nextLine();
if("X".equals(a))
break;
addBusAndPassenger(a);
}
System.out.println("There were a total of " + passengerCount + " passengers on " + busCount + " buses.");
}
}
A few things here. Other people pointed this out, but you need to pass parameters to your method. The method signature is there for a reason - your method calls must match the method signature you define.
Also, busInformation is supposed to return an int, but it returns nothing.
Also, this line:
Integer.parseInt(a);
does nothing - you throw away the result immediately. It won't modify the string in place or anything like that. (Well, I suppose that it'll throw an exception if they enter something other than an integer, but that doesn't seem to be what you're trying to do with this line).
At an absolute minimum, you should change the return type of your method to int and the change this line to return Integer.parseInt(a);.
(You also shouldn't be creating a new scanner every time like this - you should just re-use the same one).

I'm a complete beginner at java and have entangled my methods

I'm making a horse-race themed program for my mom that compares the money taken in by her employees and ties it to a horse. I've created two methods which entirely rely on each other and have no idea how to call them into my main method. I, of course, also need to add a graphical element to this at some point, and figuring out how to make the program work with decimal integers would also be ideal. My main issue right now is I need to know how to call print3largest and inputs in my main method, or how to generally make this not a dumpster fire and maybe reduce it to less than 3 methods that aren't entangled like this.
I've searched through repository websites for hours now looking for a solution, but as I have no professional experience in any kind of programming I severely lack the terminology to find an answer, assuming anyone else is stupid enough to run into the same problem I have. I'm extremely limited in my programming knowledge, with java being the only thing I've ever messed with thanks to a course in high school. Sadly, that hardly helps as it was almost entirely through an interface that was essentially just scratch.
import java.util.Scanner;
class HorseComparison
{
public static void main(String[] args)
{
//no clue how to call print3largest or inputs here without ruining everything
}
static void print3largest(int arr[], int arr_size, String firsthorse, String secondhorse, String thirdhorse)
{
int i, first, second, third;
if (arr_size < 3)
{
System.out.print(" Invalid Input ");
return;
}
third = first = second = Integer.MIN_VALUE;
for (i = 0; i < arr_size ; i ++)
{
if (arr[i] > first)
{
third = second;
second = first;
first = arr[i];
}
else if (arr[i] > second)
{
third = second;
second = arr[i];
}
else if (arr[i] > third)
third = arr[i];
}
inputs(first, second, third);
System.out.println("The horse in the lead is " + firsthorse + " with " +
first + " dollars.");
System.out.println("The runner up is " + secondhorse + " with " +
second + " dollars.");
System.out.println("Third place is " + thirdhorse + " with " +
third + " dollars.");
}
static void inputs(int first, int second, int third)
{
Scanner sc = new Scanner(System.in);
int size;
System.out.println("How many horses are competing?");
size = sc.nextInt();
int[] arr = new int[size];
System.out.println("Enter the amount of money taken in by each horse (rounded to the nearest dollar and separated by spaces)");
//For reading the element
for(int i=0;i<size;i++) {
arr[i] = sc.nextInt();
int n = arr.length;
String firsthorse;
String secondhorse;
String thirdhorse;
System.out.println("Which horse has taken in "+ first +"?");
firsthorse = sc.toString();
System.out.println("Which horse has taken in "+ second +"?");
secondhorse = sc.toString();
System.out.println("Which horse has taken in "+ third +"?");
thirdhorse = sc.toString();
print3largest(arr, n, firsthorse, secondhorse, thirdhorse);
}
}
}
I want it to display the 3 highest amounts along with the input name of the horse tied to those amounts.
I don't feel like there really is enough information about what the program is intended to do for a clear, direct answer to be provided, but I will do my best.
First, what I would suggest, is you take a good look at this program and determine how you can separate out each responsibility. For example, do you really need to call inputs from print3largest, or could you possibly call this directly from your main?
Once you have established the intent of each function, consider making each function return a result. Generally speaking, you want parameters to be immutable. Learning functional programming habits now will help you down the road.
Here is what I would do:
Copy this file to a backup file.
Start a new Java project, create your class.
Write all of your display code. That is, develop the initial user experience. What inputs do you want to ask from the user? Capture those inputs.
Given those inputs, write your core algorithm, which currently appears to be primarily in print3largest. Return those results back to the caller.
Display your results back to the end user.
This might result in more functions, but that isn't a bad thing. I would also advise that you consider creating a separate class to hold some of this logic. This will give you an opportunity to learn about objects and separation of concerns.
you can call static methods directly by the method name
print3largest()
or you can use the classname before method name example
HorseComparision.print3largest() ```
Since both methods are static and so the Main method. Static methods can be called
Directly with method name, if you are calling from inside the class. Eg : print3largest(.. args), inputs(.. args)
call using ClassName.Method name. This can be used if you are calling method from outside or inside the class. Eg: HorseComparison.print3largest(.. args), HorseComparison.inputs(.. args)

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

How to make a counter persist in 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

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

Categories

Resources