Method is outputting incorrect value? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I'm working on an assignment that is trying to output the energy consumption of appliances within a house. I have created an Appliance called ElectricCooker and an Appliance called ElectricShower. They both have exactly the same code apart from different variable names yet some how produce different outputs.
Here is the relevant code: (Sorry about the amount of code, this reproduces the program)
ElectricCooker
public class ElectricCooker extends Appliance
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 4;
}
public void cook()
{
//add code
}
#Override
public void timePasses()
{
if(varPass == isOff)
varPass = 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
ElectricMeter.getInstance().incrementConsumed(5);
int getCookerConsumed = ElectricMeter.getInstance().getElectricityUsed();
System.out.println("Electric cooker electricity consumption = " + getCookerConsumed);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
ElectricShower
public class ElectricShower extends Appliance
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses()
{
if(varPass == isOff)
varPass = 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
ElectricMeter.getInstance().incrementConsumed(5);
int getShowerConsumed = ElectricMeter.getInstance().getElectricityUsed();
System.out.println("Electric shower electricity consumption = " + getShowerConsumed);
}
}
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Appliance
abstract public class Appliance
{
public int varPass;
public int isOn;
public int isOff;
public int electricityUse, gasUse, waterUse, timeOn;
public abstract void useTime(int defaultTime);
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
public abstract void timePasses();
Appliance(int electricityUse,int gasUse,int waterUse,int timeOn)
{
electricityUse = 0;
gasUse = 0;
waterUse = 0;
timeOn = 0;
}
}
ElectricMeter
public class ElectricMeter
{
ElectricMeter() {}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
public int getElectricityUsed()
{
return electricityUsed;
}
}
House
import java.util.ArrayList;
public class House
{
ArrayList<Appliance> applianceList = new ArrayList<>();
ElectricShower calleShower = new ElectricShower(1, 1, 1, 1);
ElectricCooker calleCooker = new ElectricCooker(1, 1, 1, 1);
public void addAppliance()
{
applianceList.add(calleShower);
applianceList.add(calleCooker);
}
public void timePasses()
{
calleShower.timePasses();
calleCooker.timePasses();
//this method is called as part of the simulation to trigger a new fifteen minute period
//in the house. When it is called, it will in turn call timePasses() on all the Appliances in the House.
}
}
public class CourseworkTest {
public static void main(String[] args)
{
House callHouse = new House();
callHouse.timePasses();
}
}
Output
Electric shower electricity consumption = 5
Electric cooker electricity consumption = 10
I've been working on this for hours and I just don't understand how the exact same code can somehow produce different results? I don't see how one can be 10 and other 5 when they do the exact same thing and go through the same process. Any help is very much appreciated, thanks.

The ElectricMeter class is a singleton, meaning that one (same) instance will exist throughout the execution of your application.
First, from ElectricShower.timePasses(), you make the following call:
ElectricMeter.getInstance().incrementConsumed(5);
Then, you again make this call from ElectricCooker.timePasses(). Hence, when you output the consumption the second time, it is being reported as 10.
Using a singleton to represent the common shared electric meter for a house seems like a reasonable design decision.

Related

Can not get the right amount of people on my bus

package hw1;
public class CyrideBus {
public static final int BUS_GARAGE = -1;
private int currentCapacity;
private int numStops;
private int numPassengers;
private int currentStop;
private boolean inService;
keeps track of bus stops
public CyrideBus(int givenMaxCapacity, int givenNumStops) {
currentCapacity = givenMaxCapacity;
numStops = givenNumStops;
currentStop = BUS_GARAGE;
inService = true;
}
public int getCurrentCapacity() {
return currentCapacity;
}
public int getCurrentStop() {
return currentStop;
}
public int getNumPassengers() {
return numPassengers;
}
public int getTotalRiders() {
return numPassengers + currentCapacity+ 1;
}
public boolean isInService() {
return inService;
}
public void nextStop (int peopleOff, int peopleOn) {
currentStop= (currentStop + 1)% numStops;
peopleOff = Math.max(0, peopleOff);
peopleOn = Math.max(0, peopleOn);
numPassengers -= Math.min(peopleOff, numPassengers);
int requiredCapacity = numPassengers + peopleOn;
numPassengers = Math.min(requiredCapacity, currentCapacity);
}
public void placeInService() {
inService = true;
}
public void removeFromService() {
inService = false;
}
}
trying to make a bus route program that keeps track of people on the bus at each stop. this bus route also has a bus garage. The number one issue I am having right now is that I can not get the right amount of people on my bus keep getting
for new bus with three stops, after nextStop() six times, current stop should be 2, expected 2 but was 5
for new bus with seven stops, fter nextStop() 137 times, current stop should be 3. expected 3 but was 136
and so on

How to construct a method that needs to pass in the values from a constructor?

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

How to correctly structure an appliance?

I'm trying to correctly create a class that correctly implements the energy usage of an appliance. This includes the amount of water, gas or electricity it uses along with if the device is switched on or off and finally the amount of time that the device is being used for. When all these factors are correctly implementation, this information will then get passed onto various meters that will calculate the usage of all appliances associated with it.
For now, I have not programmed anything to be outputted, I am still focusing on structuring each appliance so that it can correctly register this information so that it can later be passed onto their respective meters.
The types of information which should be registered are these:
useTime() - Registers the amount of time that the appliance is being used for.
currentState() - If the appliance is on or off.
Constructor that stores the values of electricity, water and gas use along with the amount of time that the device has been on for.
Individual appliance actions (such as cook() or shower()).
This is what I have come up with so far for one of my appliances:
GasCooker appliance
public class GasCooker extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int totalTime;
public int incrementTime;
#Override
public int currentState(int x)
{
x = -1;
if (x == 0)
return isOff;
else
return isOn;
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 4;
}
public void cook()
{
//add code for coker to cook;
}
GasCooker(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
totalTime = 15 * incrementTime;
electricityUse = 0 * incrementTime;
gasUse = 4 * incrementTime;
waterUse = 0 * incrementTime;
timeOn = 60 * incrementTime;
}
}
This appliance is a sub class of a Cooker class which looks like this:
Cooker
public abstract class Cooker extends Appliance
{
public int isOn = -1;
public int isOff = 0;
#Override
public int currentState(int x)
{
x = -1;
if (x == 0)
return isOff;
else
return isOn;
//returns isOn;
}
public abstract void cook();
Cooker(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
}
}
Which is extended from Appliance:
Appliance
abstract public class Appliance
{
public abstract void useTime(int defaultTime);
public int currentState(int x)
{
int timeOn = -1;
int timeOff = 0;
x = 0;
if (x == 0)
return timeOff;
else
return timeOn;
}
Appliance(int electricityUse,int gasUse,int waterUse,int timeOn)
{
electricityUse = 0;
gasUse = 0;
waterUse = 0;
timeOn = 0;
}
}
The main queries that I have are these:
Do these classes look like sensible classes for registering this information?
If not, in which part have I misconceived?
This is my first assignment in which I have to define my own methods so any feedback on the sensibility of my program so far or how it could be improved would be much appreciated, thanks.

Java Error - Missing method body or declare abstract

emphasized textI've been working on this problem for a while and managed to get rid of almost all the errors on this class. This error keeps saying I'm missing method body or declare abstract but I just don't see it. I've managed to complete another class almost similar to this but this one seems to be acting strangely. Can someone please help me out? Thank you if you do.
import java.util.Scanner;
public class HockeyPlayer extends StudentAthlete
{
Scanner keyboard = new Scanner(System.in);
public static void main (String [] args)
{
HockeyPlayer athlete1 = new HockeyPlayer("Dave", 111111, 15, 3.2, 2, 3);
athlete1.writeOutput();
}
private int assist = 0;
private int goal = 0;
public HockeyPlayer()
{
super();
goal = 0;
assist = 0;
}
public int getAssist()
{
return assist;
}
public void setAssist(int newAssist)
{
if (0 >= newAssist)
{
assist = newAssist;
}
else
{
System.out.println("Invalid Assists");
System.out.println("Please enter a valid Assists");
int tempAssist = keyboard.nextInt();
setAssist(tempAssist);
}
}
public int getGoal()
{
return goal;
}
public int setGoal(int newGoal)
{
if (0 >= newGoal)
{
goal = newGoal;
}
else
{
System.out.println("Invalid Goals");
System.out.println("Please enter a valid Goals");
int tempGoal = keyboard.nextInt();
setGoal(tempGoal);
}
}
public HockeyPlayer(String initialName, int initialStudentNumber, int initialJersey, double initialGpa, int initialGoal, int initialAssist)
{
super (initialName, initialStudentNumber,initialJersey, initialGpa);
setGoal(initialGoal);
setAssist(initialAssist);
}
public HockeyPlayer(String initialName, int initialStudentNumber, int initialJersey, double initialGpa)
{
super (initialName, initialStudentNumber, initialJersey, initialGpa);
goal = 0;
assist= 0;
}
public HockeyPlayer(String initialName, int initialStudentNumber)
{
super (initialName, initialStudentNumber);
goal = 0;
assist = 0;
}
public HockeyPlayer(String initialName)
{
super(initialName);
goal = 0;
assist = 0;
}
public void writeOutput(); // THE ERROR OCCURS HERE
{
super.writeOutput();
System.out.println("Goals: " + goal);
system.out.println("Assists: " + assist);
}
}
change
public int setGoal(int newGoal)
to
public void setGoal(int newGoal)
Setter methods usually don't have a return type (and based on the fact that you don't try to return anything, you probably didn't intend it to have an int return type).
Also change
public void writeOutput();
to
public void writeOutput()

Calling variables between different classes through methods

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

Categories