(Counter/Accessor) Did I do this right?
I didn't understand the problem, so I looked at this explanation: methods - Using a Counter class to increment and decrement: java - Stack Overflow
And I came up with:
Code Java:
package counterassignment5;//http://stackoverflow.com/questions/7857600/using-a-counter-class-to-increment-and-decrement-java
public class CounterAssignment5 {
public static void main(String[] args) {
Counter count1 = new Counter();
System.out.println("Setting the counter to zero: " + count1.start());
System.out.println("");
System.out.println("Let's change the left side.");
System.out.println("");
count1.increase();
count1.increase();
System.out.println("After increasing the number by 2, the value is " + count1+ ".");
count1.decrease();
System.out.println("After decreasing it by 1, the value is " + count1 +".");
System.out.println("Finished counting. Counter value of left side is: ");
count1.output();
System.out.println("");
Counter count2 = new Counter();
System.out.println("Is " + count1 + " equal to " + count2 + "? ");
System.out.println(count1.equals(count2));
System.out.println("");
count2.increase();
System.out.println("Increased right-hand side by 1. Counter value of right side is: ");
count2.output();
System.out.println("");System.out.println("Is " + count1 + " equal to " + count2 + "? ");
System.out.println(count1.equals(count2));
System.out.println("");
count2.reset();
System.out.println("Value reset to " + count2 +".");
}
}
(Separate Class)
Code Java:
package counterassignment5;
public class Counter {
public int num = 0;
public Counter(){
this.num=0;
}
public int start(){
return num;
}
public int increase(){
return num++;
}
public int decrease(){
return num--;
}
public int reset(){
return num = 0;
}
public String toString(){
return Integer.toString(num);
}
public boolean equals (Counter counter2){
if (num == counter2.start())
return true;
else
return false;
}
public void output(){
System.out.println(num);
}}
It works as intended, but I'm wondering if I understood the problem correctly. If I didn't...that would be bad.
Re: (Counter/Accessor) Did I do this right?
Please post relevant materials on this forum with your question. This forum does not control third party activities and can not guarantee how long third parties will keep the information available, if at all. If parts go missing later, the content of this forum will have little meaning in terms of being useful for answering the same question over in the future.
Quote:
It works as intended,
Well that is a good sign...
Quote:
but I'm wondering if I understood the problem correctly. If I didn't...that would be bad.
That is the first step in problem solving. I sure hope you did not save this step til last!