I’m pretty new to Java and this has me really confused.
I have two classes. One (controlNumber) has two int fields used for numbers, one is the current number and one is the max number (once the current number reaches this it is reset to 1). The constructor initializes the current number to 1 and takes the max as a parameter (and checks that the max is positive and less than 100).
Of methods I have one that returns the current number, one that returns the max number, one that sets the max as the current, one that adds 1 to the current number (working its was towards the max) and lastly one that returns a String with the current number where it puts “0” in front if the current number is only one digit (so 5 becomes 05).
The toString looks like this:
public String toString()
{
if (currentNumber > 9) {
return Integer.toString(currentNumber);
}
else {
return ("0" + Integer.toString(currentNumber));
}
}
This class works just fine.
The second class is where I start running into problems. It has two fields which are of the class above. The constructor initializes them with two different max values. All this seems to be working.
Now I need a toString method which’ll return a String with the current value of both fields, which a “/” between and “0” in front if it’s one digit (so if day is 3 and month is 11 it’ll return “03/11”). My first thought was just to use something like what I used above with Integer.toString, but it turns out that you can’t do that (even though the fields in the controlNumber class are ints). So then I thought of using my method from above (which is in a different class) as it does most of what I want, but I don’t know how.
I hope I’ve made sense and that someone can help me figure out how to solve my problem.
If you have two fields of the type above, called a and b
You don’t need to call toString() explicitly as that is the behaviour anyway. The only difference is that if a or b is null, this will print “null” whereas calling toString() will throw a NullPointerException.
BTW You can shorten your method to