1

I m just learning coding so I got this problem " k cannot be resolved"

I have tried introducing variables before if the operator by:

double a = 2.1223;
int b = (int) a;

if(a-b > 0.5) { 
   int k = b + 1;
}

else { 
   int k = (int)b ;
}

System.out.println(k); // k cannot be resolved.why??

I expected output to be 2

instead got k cannot be resolved

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Aman
  • 1
  • 5

1 Answers1

1

The problem is with your implementation. As you see you define k in the start. But the interesting part is you define it as nothing:

int k;

The other k you have defined are inside the if and else if function and not accessible to the println() function. That means you are passing something that is undefined to be printed. That would surely result in an error. This is called scope as XtremeBaumer said. Meaning it is the property of your variables that define where they are visible and usable.

The correct way to do it would be this:

double a = 2.1223 ;
int b = (int) a ;

if(a-b > 0.5) { 
    k = b + 1;
}

else { 
    k = b; //No casting needed
}

System.out.println(k); 

That way you are not creating a new k variable every time you check with the if, or else if. What you are doing is using that k variable again by just saying k = whatever. Your problem was that you created the k variable again by doing int k.

Also, as Andy Turner pointed out you don't need to cast b to int because it already is an int.

Gaurav Mall
  • 2,372
  • 1
  • 17
  • 33