2. Define a class called Counter. An object of this class is used to count thing
ID: 3727218 • Letter: 2
Question
2. Define a class called Counter. An object of this class is used to count things, so it records 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 that displays the count on the screen. Do not define an input 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
Counter.java
public class Counter {
//Declaring instance variables
private int count;
//Zero argumented constructor
public Counter() {
setCounterToZero();
}
//This method will set the counter to zero
private void setCounterToZero() {
this.count = 0;
}
//Getter
public int getCounter() {
return count;
}
//This method will increase the count by 1
public void incCounter() {
count++;
}
//This method will decrease the count by 1
public void decCounter() {
if (count != 0) {
count--;
}
}
}
_____________________
Test.java
public class Test {
public static void main(String[] args) {
//Creating an Instance of Counter class
Counter c=new Counter();
//calling the methods on the counter class
c.incCounter();
c.incCounter();
System.out.println(c.getCounter());
c.incCounter();
c.incCounter();
System.out.println(c.getCounter());
c.decCounter();
System.out.println(c.getCounter());
}
}
______________________
Output:
2
4
3
________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.