I am trying to create a method for " winning percentage " in a player class. I know I need to incorporate total wins divided by total games played, but the code is meant to be simple so I cannot use complex code. (beginner project in computer science) Any useful feedback would be great as I have spent multiple days attempting this and getting no where. By the way, ties count as half a win.
Update: Implemented the getters into the getWinningPercentage method. Also calculated everything inside the getWinningPercentage and removed the setWinningPercentage considering it was useless code. Results were as follows:
Bob
5 wins, 1 losses, 2 ties
Winning percentage = 0.75
public class Player
{
private int numWins = 0;
private int numTies = 0;
private int numLosses = 0;
private String name;
public void setWins(int w)
{
numWins = w;
}
public int getWins()
{
return numWins;
}
public void setTies(int t)
{
numTies = t;
}
public int getTies()
{
return numTies;
}
public void setLosses(int L)
{
numLosses = L;
}
public int getLosses()
{
return numLosses;
}
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
public void incrementWins()
}
numWins++;
}
public void incrementTies()
{
numTies++;
}
public void incrementLosses()
{
numLosses++;
}
public double getWinningPercentage()
{
double totalGames = getWins() + getTies() + getLosses();
double totalWins = getWins() + (getTies() / 2.0);
double winningPercentage = (totalWins / totalGames);
return winningPercentage;
}
}
The winning percentage should be a calculated property, not a field, and not have a setter method. Instead there should only be a "getter" (public double getWinningPercentage()) method and you should calculate and return this value from within the method itself from the other fields that your class already has.
We should leave it up to you to create this method and formula yourself.
Related
I'm coding something for a theoretical airport case study and I need help with one bit. I've got 2 different integers with names: maxfuelCapacity and fuelCurrent, and I need something that says ' fuel needed to pump is '.....' being the difference between the maxfuelCapacity of the plane and the current amount. There are no real values so far. How do I go about doing that?
public static int maxfuelCapacity;
public int fuelCurrent;
public String name;
Boolean parked;
public String[] Plane = {
"BA103", "BA493", "BA209"
};
public void setName(String n) {
name = n;
}
public void setParked(Boolean o) {
parked = o;
}
public int getInt(String Maxfuelcapacity) {
return maxfuelCapacity;
}
public String getInt1 (String fuelCurrent) {
return fuelCurrent;
}
As has been mentioned in the comments, your method would look like:
public int fuelNeeded(int fuelCurrent, int maxfuelCapacity) {
if(fuelCurrent >= maxfuelCapacity) {
System.out.println("The tank already has enough");
return 0;
}
return maxfuelCapacity- fuelCurrent;
}
So you call this method in your main function that does the calculation.
I am trying to select a random method from the ones created inside the class. Is there a way to create an ArrayList and pass methods to it? I have attempted to do just that but I am getting an error when I try to add the method to the array.
public class Monkey{
private int energy;
String[] food = {"Meat", "Fish", "Bugs", "Grain"};
ArrayList<Activity> monkeyActivity = new ArrayList<>();
public Monkey(int energy) {
this.energy = energy;
}
public int getEnergy() {
System.out.println("Monkey energy level: " + energy);
return energy;
}
public void sound() {
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
monkeyActivity.add(sound()); //I get an error message here when trying
//to add the method to the array
}
public void play(){
if (energy >= 8){
System.out.println("Monkey begins to play.");
energy -= 8;
}else {
System.out.println("Monkey does not have enough energy to play");
}
System.out.println("Energy remaining: " + energy);
}
public void eat(){
Random random = new Random();
int index = random.nextInt(food.length);
System.out.println("Monkey beings to eat " + food[index]);
energy += 5;
System.out.println("Energy remaining: " + energy);
}
public void sleep(){
System.out.println("Monkey is sleeping: Zzz...");
energy += 10;
System.out.println("Energy remaining: " + energy);
}
}
This is the separate class I have made for the generic Activity..
public class Activity {
private String sleep;
private String eat;
private String sound;
private String play;
public Activity(String sleep, String eat, String sound, String play) {
this.sleep = sleep;
this.eat = eat;
this.sound = sound;
this.play = play;
}
public String getSleep() {
return sleep;
}
public String getEat() {
return eat;
}
public String getSound() {
return sound;
}
public String getPlay() {
return play;
}
public void setSleep(String sleep) {
this.sleep = sleep;
}
public void setEat(String eat) {
this.eat = eat;
}
public void setSound(String sound) {
this.sound = sound;
}
public void setPlay(String play) {
this.play = play;
}
}
You are mixing up concepts.
technical issues:
return value clash
public void sound() {
// ...
monkeyActivity.add(sound());
The return value of your method sound() is void (which means no return value), but you try to add its (not existing) return value as element to the List. This is what your compiler complains about.
unintended recursion
public void sound() {
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
monkeyActivity.add(sound());
In the last line you do a recursive call which means you call exactly the same method this code is in. If that happens unintended it almost ever results in a StackOverflowError.
writing classes without proper analysis
You have a class Activity.
But if you have a closer look this is not a single activity (as the classes name implies) but it is all possible activities.
As a result your collection monkeyActivity cannot hold single activities as elements.
Doing a wild guess I think what you wanted is more like this:
interface Activity{
void do();
}
public class Monkey{
private int energy;
String[] food = {"Meat", "Fish", "Bugs", "Grain"};
List<Activity> monkeyActivity = new ArrayList<>();
// ...
public void sound() {
monkeyActivity.add(new Activity(){
public void do(){
System.out.println("Monkey: Oooo Oooo~!");
energy -= 3;
}
});
}
You may store each method as Runnable, as any "action" is no-arg void method satisfying Runnable functional interface:
List<Runnable> actions = Arrays.asList(this::sound, this::play, this::eat, this::sleep);
to execute random method, just:
Random rnd = new Random();
actions.get(rnd.nextInt(actions.size())).run();
I'm writing a program that is based around registering the amount of energy consumption that is being used by appliances within a house. So far, I have created various meter classes such as WaterMeter, GasMeter etc. with empty methods that need to be filed with values, I have also created classes for appliances that have methods that will be used to register the consumption of energy within each appliance. What I am working on now is applying the energy values that are stored within a constructor, putting those values into a timePasses() method that will then return those values to their specific meter's methods so that they can be registered. This is what I have so far:
Appliance class example:
public class ElectricShower extends Shower
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int x = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
#Override
public int currentState()
{
if (x == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 1;
}
public void shower()
{
//call timePasses() method
}
#Override
public int timePasses()
{
if(x == isOff)
return 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 12 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 4 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter example:
public class ElectricMeter
{
public int incrementConsumed(int value)
{
}
public int incrementGenerated()
{
}
public boolean canGenerate()
{
}
public String getConsumed()
{
}
public String getGenerated()
{
}
}
What I need to do next is:
take the values of electricityUse and waterUse and store them within the timePasses() else staement
Within the timePasses() else statement, place the value of electrcityUse in the incrementGenerated() method within the ElectricMeter class and do the same for the waterUse variable.
UPDATE
Classes have been updated, still struggling to find out how to make it work.
First of all, I assume you have an Appliance class that all the appliances extends from. You should create variables in the Appliance class that stores electricity, gas and water usage:
public class Appliance
{
public int electricityUse, gasUse, waterUse, timeOn;
// ...
}
Note that you should always use getters and setters instead of public fields. I'm just lazy :D
Change your constructor so that the variables above get set:
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
// I don't know why you multiply the constant by incrementTime here. Seems weird. I think you can remove them.
this.electricityUse = 12 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 4 * incrementTime;
this.timeOn = 15 * incrementTime;
}
One way to write the else clause is to use the "Singleton Pattern".
In every meter class, write something like this:
private ElectricMeter() {}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
In the incrementConsumed method, you should accept a parameter that indicates how much to increment:
public int incrementConsumed(int value)
{
// logic here...
}
In the else clause, you can just do:
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
You should review your design.
If you need to access to a class parameter you could just define it public or better create a so called getter method that returns the value.
Example:
public class MyData {
public int counter;
}
....
// Some other class
MyData data = new MyData();
data.counter = 5;
System.out.println(data.counter);
Or
public class MyData {
private int counter;
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return this.counter;
}
}
....
// Some other class
MyData data = new MyData();
data.setCounter(5);
System.out.println(data.getCounter());
In your code I see:
public int incrementConsumed()
{
//Store value of electricityUse.
}
But this method should just return an integer and have not parameter to get an input to store.
It should be:
public void incrementConsumed(int amount) {
this.amount += amount;
}
I'm concerned about this line:
gasUse = 0 * incrementTime;
If you multiply something to 0 it will be always 0...
public class Race {
public static void main(String[] args) {
int maxSpeed = Car.getMaxSpeedForAll();
int raceLength = 1000;
Car mario = new Car(30, "Mario");
Car luigi = new Car(30, "Luigi");
while(mario.getLocation() < raceLength || luigi.getLocation() < raceLength){
mario.randomSpeedChange();
luigi.randomSpeedChange();
if (mario.getLocation() > luigi.getLocation()){
System.out.println(mario + " is in first place at " + mario.getLocation() + "!");
}
if (luigi.getLocation() > mario.getLocation()){
System.out.println(luigi + " is in first place at " + mario.getLocation() + "!");
}
if (mario.getLocation() == luigi.getLocation()){
System.out.println(mario + luigi + "are neck and neck! Who will pull ahead and take the lead?!");
}
}
}
}
import java.util.Random;
public class Car {
private int speed;
private String carName;
private int location = 0;
Random r = new Random();
private int rand;
private static int maxSpeedForAll = 120;
private static int minSpeedForAll = 0;
public Car(int speed, String name) {
this.speed = speed;
this.carName = name;
}
public int getLocation(){
return location;
}
public void setLocation(int location, int speed){
this.location += speed;
}
public static int getMaxSpeedForAll(){
return maxSpeedForAll;
}
public static void setMaxSpeedForAll(int maxSpeedForAll){
Car.maxSpeedForAll = maxSpeedForAll;
}
public static int getMinSpeedForAll(){
return minSpeedForAll;
}
public static void setMinSpeedForAll(int minSpeedForAll){
Car.minSpeedForAll = minSpeedForAll;
}
public int getSpeed(){
return speed;
}
public void setSpeed(int speed){
if(speed <= maxSpeedForAll){
this.speed = speed;
} else {
this.speed = maxSpeedForAll;
}
if(speed < minSpeedForAll){
this.speed = minSpeedForAll;
}
}
public String getName(){
return carName;
}
public void setName(String name){
this.carName = name;
}
public String toString(){
String result;
result = carName;
return result;
}
public void accelerate(int rand){
if (rand > 0){
speed += 10;
}
}
public void decelerate(int rand){
if (rand < 0){
speed += -10;
}
}
public void randomSpeedChange(){
setRand(r.nextInt(10 - -10) + -10);
}
public int getRand() {
return rand;
}
public void setRand(int rand) {
this.rand = rand;
}
}
So I am currently doing an assignment where I need to race two cars in a set race length. To determine the current position of the cars in the race, I have to add the value of the cars' positions to the value of the cars' speed, and that value has to be displayed in the main. Simple enough I suppose, but the speed of the cars are altered randomly every time the race loops on an interval of -10 to 10. I have been working on different solutions to this for a few days and I am no closer to actually making this code work how it is meant to work, and if someone could give me some pointers on what the heck I am doing wrong I would greatly appreciate it.
In summary, I am attempting to:
1) Add an integer (location) to an integer (speed) and return it to the main.
2) Change one integer (speed) by adding/subtracting randomly between -10 and 10 during every loop before adding it to the other integer (location).
I apologize in advance if this was answered somewhere already - I have searched this site high and low for a similar problem with a solution and couldn't really find any that was the same situation as my problem.
A few things for a possible result:
After the value of rand is determined, you should perform a check to see whether or not to call accelerate or decelerate. These methods should only modify the value of speed.
accelerate and decelerate should call setSpeed using the modified value of speed as an argument.
After the speed is set, setLocation should be called. If the location parameter in the setLocation method will not be used, it does not need to be listed as a formal parameter.
This line does not compile:
System.out.println(mario + luigi + "are neck and neck! Who will pull ahead and take the lead?!");
You need to use your toString() method in order to make this work. I'd also recommend adding the word "and" as well as spaces because it currently outputs "MarioLuigiare neck and neck! (etc.)"
The way your code is currently written; mario.speed and luigi.speed are never modified, keeping both at a constant speed throughout the race. You need to either call the accelerate() and decelerate() methods or include code in randomSpeedChange() to modify their speed
You also never change their location, keeping them perpetually at the starting line. You should call the setLocation() method for each after changing their speed to fix this.
I would also recommend modifying the decelerate() method to ensure speed never falls below zero, unless you intend for them to be able to go backwards (the first time I ran it after fixing the issues I mentioned above, they ended up with huge negative numbers for location).
Here are the changes I made to the code (besides adding toString() to the line mentioned at the top of my answer):
The randomSpeedChange() method:
public void randomSpeedChange(){
setRand(r.nextInt(10 - -10) + -10);
accelerate(rand);
decelerate(rand);
}
The while loop in the main method:
while(mario.getLocation() < raceLength || luigi.getLocation() < raceLength){
mario.randomSpeedChange();
mario.setLocation();
luigi.randomSpeedChange();
luigi.setLocation();
//all the if statements here
}
The setLocation() method:
public void setLocation(){
location += speed;
}
(This method worked fine, but the parameters were unnecessary.)
The decelerate() method:
public void decelerate(int rand){
if ((rand < 0) && (speed >= 10)){
speed += -10;
}
}
This ensures that speed is at least 10 before reducing it, to make sure that it never falls below 0.
It seems you don't change speed and location in the loop block. I guess this maybe what you need:
Main class:
public class Race {
public static void main(String[] args) {
int maxSpeed = Car.getMaxSpeedForAll();
int raceLength = 1000;
Car mario = new Car(30, "Mario");
Car luigi = new Car(30, "Luigi");
while(mario.getLocation() < raceLength || luigi.getLocation() < raceLength){
if (mario.getLocation() > luigi.getLocation()){
System.out.println(mario + " is in first place at " + mario.getLocation() + "!");
}
if (luigi.getLocation() > mario.getLocation()){
System.out.println(luigi + " is in first place at " + mario.getLocation() + "!");
}
if (mario.getLocation() == luigi.getLocation()){
System.out.println(mario.getName() + luigi.getName() + "are neck and neck! Who will pull ahead and take the lead?!");
}
//change the speed randomly
mario.randomSpeedChange();
luigi.randomSpeedChange();
//change the location according to speed
mario.setLocation(mario.getLocation(), mario.getSpeed());
luigi.setLocation(luigi.getLocation(), luigi.getSpeed());
}
}
}
Car class:
import java.util.Random;
public class Car {
private int speed;
private String carName;
private int location = 0;
Random r = new Random();
private int rand;
private static int maxSpeedForAll = 120;
private static int minSpeedForAll = 0;
public Car(int speed, String name) {
this.speed = speed;
this.carName = name;
}
public int getLocation(){
return location;
}
public void setLocation(int location, int speed){
this.location += speed;
}
public static int getMaxSpeedForAll(){
return maxSpeedForAll;
}
public static void setMaxSpeedForAll(int maxSpeedForAll){
Car.maxSpeedForAll = maxSpeedForAll;
}
public static int getMinSpeedForAll(){
return minSpeedForAll;
}
public static void setMinSpeedForAll(int minSpeedForAll){
Car.minSpeedForAll = minSpeedForAll;
}
public int getSpeed(){
return speed;
}
public void setSpeed(int speed){
if(speed <= maxSpeedForAll){
this.speed = speed;
} else {
this.speed = maxSpeedForAll;
}
if(speed < minSpeedForAll){
this.speed = minSpeedForAll;
}
}
public String getName(){
return carName;
}
public void setName(String name){
this.carName = name;
}
public String toString(){
String result;
result = carName;
return result;
}
public void accelerate(int rand){
if (rand > 0){
speed += 10;
}
}
public void decelerate(int rand){
if (rand < 0){
speed += -10;
}
}
public void changeSpeed(int rand) {
if (rand > 0){
speed += 10;
}
if (rand < 0){
speed += -10;
}
}
public void randomSpeedChange(){
setRand(r.nextInt(10 - -10) + -10);
changeSpeed(rand);
}
public int getRand() {
return rand;
}
public void setRand(int rand) {
this.rand = rand;
}
}
I'm doing an assignment for my computer science class.
I've done quite a bit of the assignment, but I'm having a little bit of trouble pulling the individual variables from the classes. We are just getting into classes and objects and this is our first assignment regarding them so I don't completely understand all of it. So far I've been able to print out the teams, but I haven't been able to pull the individual wins, losses, OTL and OTW so that I can compute whether or not each individual team is a winning team.
What I have done so far is create a class called winningRecord and getPoints, which returns a boolean deciding whether it's a winning team or not. (The formula for a winning team is if the points are > Games Played * 1.5 (as that is an even record).
I don't know how to pull the stats, as it has to be written in the HockeyTeam class. I have set it up so that the constructor sets the variables publicly so that the can be accessed, but as far as accessing them, I'm stumped.
As far as storing them once I am able to access them, would I just make a parallel method that has the points for each team, with just one digit assigned to each bin?
Here is all of the code, thanks for looking.
public class A1Q2fixed {
public static void main(String[] parms) { // main method
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() { // processing method
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams) {
for (int i = 0; i < hockeyTeams.length; i++) {
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams() {
}
public static HockeyTeam[] createTeams() {
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count = 0; (count < teams.length) && (team != null); count++) {
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
/* hockey team class *******/
class HockeyTeam {
public String name;
public int wins;
public int otw;
public int otl;
public int losses;
public HockeyTeam(String name, int wins, int otw, int otl, int losses) {
this.name = name;
this.wins = wins;
this.otw = otw;
this.otl = otl;
this.losses = losses;
}
public String toString() {
System.out.println(name);
return " W:" + wins + " OTW:" + otw + " OTL:" + otl + " L:" + losses;
}
public static boolean[] winningRecord(HockeyTeam[] hockeyTeam) {
boolean array[] = new boolean[hockeyTeam.length];
String name;
int wins;
int otw;
int otl;
int losses;
for (int i = 0; i < hockeyTeam.length; i++) {
System.out.println(HockeyTeam.name);
}
return array;
}
public static int getPoints() {
int points = 0;
return points;
}
}
/* hockey teams class *******************/
class HockeyTeams {
private static int count = 0;
private static HockeyTeam[] hockeyTeams = {
new HockeyTeam("Canada", 5, 3, 0, 0),
new HockeyTeam("Russia", 5, 1, 1, 2),
new HockeyTeam("Finland", 3, 2, 1, 3),
new HockeyTeam("Sweden", 4, 1, 1, 4),
new HockeyTeam("USA", 1, 2, 2, 3), };
public static int getNumberTeams() {
return hockeyTeams.length;
}
public static HockeyTeam getTeam() {
HockeyTeam hockeyTeam;
hockeyTeam = null;
if (count < hockeyTeams.length) {
hockeyTeam = hockeyTeams[count];
count++;
}
return hockeyTeam;
}
}
Thanks,
Matt.
Sorry but I was only able to understand only a part of your question,from what I understood it seems you are not able to access individual wins, losses, OTL and OTW. I hope this answers your question if not please clarify a bit
To access OTL,OTW have a loop as below:
public class A1Q2fixed
{
public static void main(String[] parms) // main method
{
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() // processing method
{
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
for(HockeyTeam h:hockeyTeams)
{
System.out.println(h.losses);//To access and print losses
System.out.println(h.otw);//To access and print otw
System.out.println(h.otl);//To access and print otl
}
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams)
{
for (int i = 0; i < hockeyTeams.length; i++)
{
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams()
{
}
public static HockeyTeam[] createTeams()
{
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count=0; (count<teams.length) && (team!=null); count++)
{
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
Also declare name as Static in HockeyTeam