I am working on a classroom exercise that is producing unexpected output. Hopefully someone can explain what I am missing.
I am fine up to the last 4 lines of Class1, then I'm a bit confused.
public class Class1 {
public static void main(String[] args){
Class2 val1 = new Class2 ();
Class2 val2 = new Class2 ();
val1.set (3);
val2.set (4);
for (int num = 11; num>=1; num -=4){
val1.change (num);
val2.change(val1.get());
System.out.println("Val1 " + val1);
System.out.println("Val2 " + val2);
}
val1 = val2;
val1.change(3);
val2.change(val1.get());
System.out.println(val1.get());
System.out.println(val2.get());
}
} // end Class1
Here is Class2
public class Class2 {
private int num1;
private int num2;
public void set (int inValue){
num1 = inValue;
num2 = inValue + 2;
}
public void change (int inValue){
num1++;
num2 += inValue;
}
public int get (){
return num1 + num2;
}
public String toString (){
return num1 + " = " + num2;
}
}
The output I am expecting from the code is as follows:
Val1 4 = 16
Val2 5 = 26
Val1 5 = 23
Val2 6 = 54
Val1 6 = 26
Val2 7 = 86
97
191
However the output the code produces when I run it is:
Val1 4 = 16
Val2 5 = 26
Val1 5 = 23
Val2 6 = 54
Val1 6 = 26
Val2 7 = 86
195
195
I don't understand where the 195 is coming from.
Before the last 4 lines, we set val1 equal to val2, so now both are (num1 = 7, num2 = 86) In the last 4 lines of Class1:
val1.change(3); // should change val1 to (num1 = 8, num2 = 89)
val2.change(val1.get()); // val.get() should return (8+89)=97,
pass that in as a parameter to val2.change() should result in val2(num1 = 8, num2 = 183)
System.out.println(val1.get()); // should produce (8+89)=97
System.out.println(val2.get()); // should produce (8+183)=191
Yet neither of these numbers are what is output. What am I missing?