Levels Tought:
Elementary,Middle School,High School,College,University,PHD
Teaching Since: | Apr 2017 |
Last Sign in: | 36 Weeks Ago, 4 Days Ago |
Questions Answered: | 4870 |
Tutorials Posted: | 4863 |
MBA IT, Mater in Science and Technology
Devry
Jul-1996 - Jul-2000
Professor
Devry University
Mar-2010 - Oct-2016
New to this course, read the chapters but still not making progress. Attached is what i have.
Program Assignment
Write a counter class in its own file. This will allow your counter to be used by any program.
The counter must be able to increment and decrement by one. It must never go below zero. toString and equals must be implemented and tested correctly. (toString and equals are covered in depth in your text) System.out.println("”+c1) must work and if(c1.equals(c2)) must work where c1 and c2 are instances of your counter. Include an override of the default constructor that sets the counter to zero and a constructor that allows you to set the count.
Counter.java
public class Counter
{
//private variable
private int count;
//initializes the count to zero
public Counter()
{
count = 0;
}
void setcounter(int i)
{
if(i>0) count=i;
}
public Counter(int i)
{
if(i>0) count=i;
}
//adds 1
void Increment()
{
count=count++;
}
//subtracts 1
void Decrement()
{
if(count>=0)
count--;
else
System.out.println("");
System.out.println("");
System.out.println("Error - Attempted to subtract 1 widget from 0
widgets.");
}
// Returns the current count as a string.
@Override
public String toString()
{
return count + "";
}
public boolean equals(Counter other)
{
return(count==other.count);
}
// Resets the count back to 0.
public void reset()
{
count = 0;
System.out.println("Number of widgets reset to 0.");
}
}
public class NewCounter {
public static void main(String args)
{
// Make a new counter
Counter counter1 = new Counter();
Counter counter2 = new Counter();
// TODO code application logic here
System.out.println("This program creates and uses Counters");
System.out.println();
System.out.println("Initial State"); System.out.println("counter1 is at " + counter1);
System.out.println("counter2 is at " + counter2);
System.out.println("counter1 " + (counter1.equals(counter2)?
"equals":"not equals") + " counter2");
counter1.Decrement();
counter1.setcounter(1);
counter2.Increment();
System.out.println("");
System.out.println("State after first test");
System.out.println("counter1 is at " + counter1);
System.out.println("counter2 is at " + counter2);
System.out.println("counter1 " + (counter1.equals(counter2)?
"equals":"not equals") + " counter2");
System.out.println("");
System.out.println("State after second test");
System.out.println("counter1 is at " + counter1);
System.out.println("counter2 is at " + counter2);
System.out.println("counter1 " + (counter1.equals(counter2)?
"equals":"not equals") + " counter2");
System.out.println("");
System.out.println("Process Complete"); }
}