This is a question from a past exam paper. The question asks to declare a variable c of type Counter in a new class. I should then intialise it to a new instance of Counter with n taking a value of 100. I must then increment its n field twice. Then print the value of the n field to System.out.
I have done both classes, but i am not sure about the Counter2 class. I think i may be declaring the Counter variable wrong.
public class Counter {
private int n;
public int x;
public Counter(int theN){
this.n=theN;
}
public int getN(){
return n;
}
public void inc(){
x = 1+ getN();
}
}
public class Counter2{
Counter c;
public int incrementTwice(){
int i = 0;
while(i<2){
c.inc();
i++;
}
return c.x;
}
public static void main (String[] args){
c = new Counter(100);
int finalResult = c.getN();
System.out.println(finalResult);
}
}
In
inc()you are not actually incrementingn. You are settingxton+1.So, it does not matter how many times you run
inc, before the first run you will haven = initial Valueandx=0, after the first run and following you haven = initialValueandx = n + 1