Page 1 of 1

About Question enthuware.ocpjp.v11.2.3560

Posted: Fri Oct 30, 2020 11:25 am
by lizibfranca
instance fields cant be of type var. This code will not compile.

the question is below.

--

Given:
public class LoopTest {
var k = 5;
public boolean checkIt(int k){
return k-->0?true:false; }
public void printThem(){
while(checkIt(k)){
System.out.print(k); } }
public static void main(String[] args) {
new LoopTest().printThem(); } }
What changes should be made so that the program will print 54321?


Answer: Replace System.out.print(k); with System.out.print(k--);

Explanation
Observe that the method parameter k in checkIt shadows the instance variable k. Therefore, any changes made to k in checkIt will not affect the instance variable k. For checkIt method to access the instance variable k, you need to do this.k. k-->0 means, first compare the value of k with 0, and then reduce it by 1. (As opposed to --k>0, which means, first reduce the value of k by 1 and then compare with 0). In the printThem method, k refers to the instance variable. You need to reduce it by 1 after each iteration. Therefore, System.out.print(k--); will do.

Re: About Question enthuware.ocpjp.v11.2.3560

Posted: Fri Oct 30, 2020 2:10 pm
by admin
You are right. It should be int instead of var. Fixed.
thank you for your feedback!