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.
About Question enthuware.ocpjp.v11.2.3560
Moderators: Site Manager, fjwalraven
-
- Posts: 1
- Joined: Fri Oct 30, 2020 11:13 am
- Contact:
Online
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v11.2.3560
You are right. It should be int instead of var. Fixed.
thank you for your feedback!
thank you for your feedback!
Who is online
Users browsing this forum: No registered users and 8 guests