Define a class called Counter.An object of this class is used to count things,so
ID: 3654977 • Letter: D
Question
Define a class called Counter.An object of this class is used to count things,so it record a count that is a nonnegative whole number.Include methods to set the counter to 0, to increase the count by 1, and to decrease the count by 1.Be sure that no method allows the value of the counter to become negative.Also include an accessor method that returns the current count value,as well as a method. The only method that can set the counter is the one that sets it to zero.Write a program to test your class definition.(Hint:you need only one instance variable.)Explanation / Answer
public class CounterDemo { public static void main(String[] args) { // Make a new counter Counter counter = new Counter(); System.out.println("Initial value is " + counter.getValue()); // Test the increment and toString() methods. counter.increment(); counter.increment(); System.out.println( "After two increments, value is " + counter); // Test the decrement method counter.decrement(); System.out.println("After one decrement, value is " + counter); // Test the output() method System.out.println("Result of calling counter.output() :"); counter.output(); // Make a second counter to test equals. Counter counter2 = new Counter(); System.out.println(counter + " equals " + counter2 + "? " + counter.equals(counter2)); // Increment counter2 so that they are equal counter2.increment(); System.out.println(counter + " equals " + counter2 + "? " + counter.equals(counter2)); // Reset counter2 to zero counter2.resetToZero(); System.out.println("After resetting to zero, value is " + counter2); } } /** Class that counts things. */ class Counter { /** Current value of the counter */ public int value = 0; public Counter(){ this.value = 0; } public int getValue() { return value; } public int increment() { return value++; } public int decrement() { return value--; } public int resetToZero() { return value=0; } public String toString() { return Integer.toString(value); } /** Prints the current value to System.out */ public void output() { System.out.println("Counter value is " + value); } } output Initial value is 0 After two increments, value is 2 After one decrement, value is 1 Result of calling counter.output() : Counter value is 1 1 equals 0? false 1 equals 1? false After resetting to zero, value is 0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.