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.