About Question enthuware.ocpjp.v11.2.3560

All the posts and topics that contain only an error report will be moved here after the error is corrected. This is to ensure that when users view a question in ETS Viewer, the "Discuss" button will not indicate the presence of a discussion that adds no value to the question.

Moderators: Site Manager, fjwalraven

Post Reply
lizibfranca
Posts: 1
Joined: Fri Oct 30, 2020 11:13 am
Contact:

About Question enthuware.ocpjp.v11.2.3560

Post 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.

Online
admin
Site Admin
Posts: 10384
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocpjp.v11.2.3560

Post by admin »

You are right. It should be int instead of var. Fixed.
thank you for your feedback!

Post Reply

Who is online

Users browsing this forum: No registered users and 8 guests