-Define a class called Counter . An object of this class is used to count things
ID: 3690386 • Letter: #
Question
-Define a class called Counter. An object of this class is used to count things. The class can be used to either count nonnegative whole numbers or nonnegative floating point numbers. The class should include two instance variables; one long and one double.
-The class should include a three Constructors; a default Constructor with no parameters which initializes both variables to 0, and one Constructor each for initializing each instance variable.
-The class should include two overloaded methods; add (2) and subtract (2). Each overloaded method is responsible for the count of each variable. Be sure that no method allows the value of the counter to become negative.
- The class should include a toString() method, which can be used to display the two instance variables.
- The class should include a static method reset(), which will set each of the two variables to 0.
- Write a program to test your class definition.
- Each method in the class should contain documentation as to its function.
Explanation / Answer
class Counter
{ int a;
int b;
public:
pointer() //constructors with and without parameters
{a=0;
b=0;
}
pointer(int c,int d)
{a=c;
b=d;
}
void add(int p)// overloaded add and subtract functions
{ a=a+p;
return a;
}
void add( float z)
{ b=b+z;
return b;
}
void subtract(int p)
{ a=a-p;
return a;
}
void subtract(float z)
{ b=b-z;
return b;
}
public String toString()
{{System.out.println("The instance variables are " ,a,b);
}
void reset()
{a=0;
b=0;
}
import java.util.*; //tester class
public class CounterTester {
public static void main(String[] args) {
Counter counter = new Counter();
Counter counter1 = new Counter(10.20);
counter.add(10);
counter.add(11.0);
counter.subtract(2);
counter.subtract(5.0);
System.out.println( "the values are here" + counter.toString());
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.