Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

6.Programming Problem: a.Create a Counter class that supports the following: i.

ID: 3721363 • Letter: 6

Question

6.Programming Problem:

a.Create a Counter class that supports the following:

i. increment() Increments the counter by one

ii. increment(int value) Increments the counter by value; value > 1

iii. decrement() Decrements the counter by one

iv. decrement(int value) Decrements the counter by value; value > 1

v. reset() Resets the counter to zero

vi. toString() Used to list the value/values of data members

b. Create a main() method the instantiates the Counter class and demonstrates all of the aforementioned methods.

Sample run for question #6:

$ useCounter

Initial value of Counter: 0

Value of Counter after increment() being called twice: 2

Value of Counter after increment(3): 5

Value of Counter after decrement(2): 3

Value of Counter after decrement(): 2

Value of Counter after reset(): 0

Explanation / Answer

CounterClass.java

public class CounterClass {

public static int counter = 0;

public static int increment(){

counter = counter +1;

return counter;

}

public static int increment(int step){

counter = counter +step;

return counter;

}

public static int decrement(){

counter = counter-1;

return counter;

}

public static int decrement(int step){

counter = counter - step;

return counter ;

}

public static int reset(){

counter = 0;

return counter;

}

}

Main method Class

public class CounterClassDemo {

public static void main(String[] args) {

CounterClass c1 = new CounterClass();

int counter=0;

counter = c1.increment();

counter = c1.increment();

System.out.println("Value of Counter after increment() being called twice:"+counter);

counter = c1.increment(3);

System.out.println("Value of Counter after increment(3) : "+counter);

counter = c1.decrement(2);

System.out.println("Value of Counter after decrement(2) : "+counter);

counter = c1.decrement();

System.out.println("Value of Counter after decrement() : "+counter);

counter = c1.reset();

System.out.println("Value of Counter after reset() : "+counter);

}

}