I am trying to use the Die class when writing a PairOfDice class. Here is the Die class:
public static class Die {
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
if(value > 0 && value <= MAX)
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now what I am trying to do is to use this class to write a similar class called PairOfDice. I want similar methods of rolling the dice, setting the face value, and so on. However I have never done this before so I'm not sure how to approach this. Here is what I have so far:
public static class PairOfDice {
Die die1 = new Die();
Die die2 = new Die();
public PairOfDice()
{
????
}
public int rollPair()
{
????
}
}
I'm not sure how to appropriately use these objects. Please keep in mind I am a beginner in java/programming.
You don't appear to need anything in the constructor, you've initialized the die fields where you declared them. Just call them in your method. Something like,
public int rollPair()
{
return die1.roll() + die2.roll();
}
Related
this is the qa:
Define a class called MoreSpeed which extends the following class, and which provides a new method called incSpeed() which adds 1 to the inherited variable length.
this is my answer:
public class Speed {
private int length = 0;
public int getSpeed () { return length; }
public void setSpeed (int i) {
if (i > 0) {
length = i;
}
}
}
public class MoreSpeed extends Speed {
private int length;
public int incSpeed() {
return length+1;
}}
its says that the syntax is good but the class operation is wrong.
please help me,thanks.
No. You are shadowing the length from Speed. Instead, implement incSpeed with getSpeed() like
public int incSpeed() {
return getSpeed() + 1;
}
If you are supposed to modify it as well then use setSpeed(int) to do so
public int incSpeed() {
int s = getSpeed() + 1;
setSpeed(s);
return s;
}
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...
I'm very new to Java, and am having trouble with an assignment. For some reason, I'm only getting null. Is there something I did wrong?
public class Dieprint
{
public static void main(String[]args)
{
Die die1 = new Die();
die1.roll();
die1.toString();
die1.print();
}
}
class Die
{
//instance variables
private int faceValue;
private int numSides;
private String faceValue2;
//constructor
public Die()
{
numSides = 6;
faceValue = roll();
}
//accessors
public int getValue() { return faceValue; }
//mutators
public int roll()
{
faceValue = (int)(Math.random()*numSides + 1);
return faceValue;
}
//methods
public String toString()
{
String faceValue2 = ("" + faceValue);
return faceValue2;
}
public String print()
{
System.out.println("Result is: " + faceValue2);
return faceValue2;
}
}
I've tried to make the toString method return faceValue itself, but that didn't work at all.
I'd really appreciate any help with this.
In the method public String toString() what you did is initiate a new variable faceValue2. Even though you already have that variable in your field, when you wrote String faceValue2 = {"" + faceValue) (emphasis on the word String) you are now pointing to a another variable called faceValue2, and it is no longer the faceValue2 in your field.
If you walk through your code, the printing is happening in your print method, where there exists a variable called faceValue2. This variable points towards the faceValue2 in your field, which since it has not been changed in your toString() method is still null. Therefore when you print, you get null.
What you can do to solve this problem is simply remove the keyword String, making your code
public String toString(){
faceValue2 = "" + faceValue;
return faceValue2;
}
This will guarantee that you are changing the variable in your field which will in turn change the variable in your print() method, and therefore, change the output you get after running the code.
Suggestions:
Get rid of the faceValue2 variable and the print() method as they serve no purpose other than to confuse.
Instead, print out the toString result: System.out.println(die1);. This will print out the value returned from Die's toString method.
For example
public class DiePrint {
public static void main(String[] args) {
Die die = new Die();
System.out.println(die);
die.roll();
System.out.println(die);
}
}
class Die {
private static final int DEFAULT_NUM_SIDES = 6;
private int faceValue;
private int numSides;
// default constructor
public Die() {
this(DEFAULT_NUM_SIDES);
}
// if numSides can vary, then have a constructor that will
// allow one to set it.
public Die(int numSides) {
this.numSides = numSides;
roll(); // no need to set numSides when rolling. it's already done
}
// accessors should reflect the field name
public int getFaceValue() {
return faceValue;
}
public int getNumSides() {
return numSides;
}
// mutators
public int roll() {
faceValue = (int) (Math.random() * numSides + 1);
return faceValue;
}
// methods
public String toString() {
String faceValue2 = ("" + faceValue);
return faceValue2;
}
}
So I made a die class that is supposed to create die, and then allow me to roll them, pull their values and number of sides. My problem now is that I cannot roll the die during testing as it throws a NullPointerException.
Here's the die class code:
package com.catalyse.die;
import java.util.Random;
public class Die
{
// instance variables
private static int dieNum = 0;
private int myDieValue;
private int myDieSides;
private Random rand;
// Dice Class Constructors
public Die()
{
dieNum++;
this.myDieValue = 1;
this.myDieSides = 4;
}
public Die(int numSides)
{
if ((numSides < 4) || (numSides > 100)) {
System.out.println("Error! You cannot have more than 100 sides or less than four!");
System.exit(0);
}
else {
myDieSides = numSides;
myDieValue = 1;
}
}
// getter methods
public int getDieSides()
{
System.out.println(myDieSides);
return 0;
}
public int getDieValue()
{
System.out.println(myDieValue);
return 0;
}
// setter methods
private void setDieSides(int newNumSides)
{
myDieSides = newNumSides;
}
public void rollDie()
{
myDieValue = (rand.nextInt(myDieSides) + 1);
}
// other methods
public void printDie(int dieNum)
{
if (dieNum == 1) {
System.out.println("Die Value: "+myDieValue);
}
else {
System.out.println("Die "+dieNum+" Value: "+myDieValue);
}
}
}
Here is the testing class.
package com.catalyse.die;
public class TestDieClass
{
public static void main(String [] args)
{
Die One = new Die();
Die Two = new Die(50);
Die Three = new Die(99);
One.getDieSides();
One.getDieValue();
Two.getDieSides();
Two.getDieValue();
Three.getDieSides();
Three.getDieValue();
One.rollDie();
Two.rollDie();
Three.rollDie();
One.getDieValue();
Two.getDieValue();
Three.getDieValue();
}
}
Here is the error
4
1
50
1
99
1
Exception in thread "main" java.lang.NullPointerException
at com.catalyse.die.Die.rollDie(Die.java:83)
at com.catalyse.die.TestDieClass.main(TestDieClass.java:27)
myDieValue = (rand.nextInt(myDieSides) + 1);
You haven't initialized rand so rand is null
So,
private Random rand= new Random();
So I'm making a die class that can create and roll a die, return the value and the size. I'm trying to figure out how to tell the program how many of them have been created so that I can have a response be different based on how many there are. IE I want the response from printDie to be Die Value: 5 if there is only one die, and Die 1 Value: 5 if there is more than one.
Here's my code so far.
package com.catalyse.die;
import java.util.Random;
public class Die
{
// instance variables
private int myDieValue;
private int myDieSides;
private Random myRandom;
// Dice Class Constructors
public Die()
{
this.myDieValue = 1;
this.myDieSides = 4;
}
public Die(int numSides)
{
if ((numSides < 4) || (numSides > 100)) {
System.out.println("Error! You cannot have more than 100 sides or less than four!");
System.exit(0);
}
else {
myDieSides = numSides;
}
}
// getter methods
public int getDieSides()
{
return myDieSides;
}
public int getDieValue()
{
return myDieValue;
}
// setter methods
private void setDieSides(int newNumSides)
{
myDieSides = newNumSides;
}
public void rollDie()
{
Random rand = new Random();
int i = (rand.nextInt(myDieSides) + 1);
myDieValue = i;
}
public void printDie(int dieNum)
{
if (dieNum == 1) {
System.out.println("Die Value: "+myDieValue);
}
else {
System.out.println("Die "+dieNum+" Value: "+myDieValue);
}
}
}
You can have static field in your class which could be incremented in the constructor always. The reason why is it should be static is because, static fields are shared by all instances of a class, thus a local copy of the field won't be created for each of the instances you create.
private static int counter = 0;
public Die()
{
counter++;
// Other stuffs
}
// Have a getter method for the counter so that you can
// get the count of instances created at any point of time
public static int getCounter() {
return counter;
}
And then you can call the above method in your calling method like this
void someMethodInAnotherClass() {
int instanceCount = Die.getCounter(); // You need to call static method using the Class name
// other stuffs.
}
Use an static member, that is a 'class' variable, not a 'instance' variable:
private static int count = 0;
In the constructor:
public Die()
{
count++;
this.myDieValue = 1;
this.myDieSides = 4;
}
And a getter:
public static int getCount() {
return count;
}
Use a static variable
public class Die{
static int dieCount = 0;
public Die(){
dieCount++;
}
}
Every time a Die object is created, the count will increase
public static void main(String[] args){
Die die1 = new Die();
Die die2 = new Die();
int count = Die.dieCount;
}
See what is my solution for counting objects in my application
import java.util.Map;
import java.util.TreeMap;
public abstract class ObjectCounter {
private static Map<String, Long> classNameCount = new TreeMap<String, Long>();
public ObjectCounter() {
String key = this.getClass().getName();
if (classNameCount.containsKey(key)) {
classNameCount.put(key, classNameCount.get(key) + 1);
} else {
classNameCount.put(key, 1L);
}
}
public static <T extends ObjectCounter> long getCount(Class<T> c) {
String key = c.getName();
if (classNameCount.containsKey(key)) {
return classNameCount.get(key);
} else {
return 0;
}
}
public static long totalObjectsCreated() {
long totalCount = 0;
for (long count : classNameCount.values()) {
totalCount += count;
}
return totalCount;
}
}
Now extends ObjectCounter class
See below
package com.omt.factory;
public class Article extends ObjectCounter {
}
Now all your other classes are extending Article classes
package com.omt.factory;
public class Bio extends Article {
}
Now here is our main class
package com.omt.factory;
public class Main {
public static void main(String... a) {
Bio b = new Bio();
Bio b1 = new Bio();
Bio b2 = new Bio();
Bio b3 = new Bio();
Bio b4 = new Bio();
com.omt.temp.Bio bio = new com.omt.temp.Bio();
// Total Objects are created
System.out.println("Total Objects Created By Application :" + ObjectCounter.totalObjectsCreated());
// Get Number Of Objects created for class.
System.out.println("[" + com.omt.temp.Bio.class.getName() + "] Objects Created :"
+ ObjectCounter.getCount(com.omt.temp.Bio.class));
System.out.println("[" + Bio.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Bio.class));
System.out.println("[" + Maths.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Maths.class));
}
}
From this article