Reputation: 139
Building a program that will have imperial weights (stones, pounds and ounces), and I need ranges for the pounds and ounces (ie ounces 0-15), once the ounces int goes above 15, then pounds will increment by 1, with the same happening to pounds so that stones increments by 1.
I am fairly new to Java so this is new to me and I've no idea how to get it started.
public class NewWeight {
private int stones = 0;
private int pounds = 0;
private int ounces = 0;
public NewWeight (int stones, int pounds, int ounces) {
...
Say when there is an input of 18 ounces, the output would be 1 pound and 2 ounces
, another example being 224 ounces so that the output would end up being 1 stone, 0 pounds, 0 ounces
Upvotes: 1
Views: 51
Reputation: 272370
You don't have to use 3 variables ounces
, pounds
and stones
here. All these three represent one quantity - weight.
You can just store the weight in ounces and nothing else:
private int weightInOunces;
Then you can add methods such as getPounds
, getStones
and getOunces
, which do maths on weightInOunces
.
For example:
public int getPounds() {
return weightInOunces % 224 / 16;
}
public int getOunces() {
return weightInOunces % 16;
}
public int getStones() {
return weightInOunces / 224;
}
Setters could be implemented like this:
public int setPounds(int pounds) {
int stones = getStones();
weightInOunces = stones * 244 + getOunces() + pounds * 16;
}
public int setOunces(int ounces) {
int pounds = getPounds();
weightInOunces = pounds * 16 + ounces;
}
public int setStones(int stones) {
weightInOunces = stones * 244 + weightInOunces % 244;
}
The constructor could be implemented like this:
public Weight(int stones, int pounds, int ounces) {
weightInOunces = stones * 224 + pounds * 16 + ounces;
}
To achieve the output, you can also add a toString
method that outputs the weight in the format x stones, x pounds, x ounces
.
Upvotes: 3