Home > Back-end >  Java switch statement giving error: "boolean cannot be converted to int"
Java switch statement giving error: "boolean cannot be converted to int"

Time:10-31

so i was trying to use the switch statement to set bounds for position x and position y. i have provided my code as well as error message below. Also i am new into java so it might be a dumb question on my part but i honestly do not know any better at the moment.

public class Point{
    // Define instance variables
    private int posX;
    private int posY;
    
    //Constructor for object Point
    public Point(int x, int y){
        posX = x;
        posY = y;
    }
    //toString
    public String toString() {
   String point = null;
   point = "("   posX   " , "   posY   ")";
   return point;
}
    //move method
    public void move(int x, int y){
        int tmpX = posX   x;
        int tmpY = posY   y;
        
        switch (tmpX){
            case tmpX > 100:
                posX = 100;
                break;
            case tmpX < 0:
                posX = 0;
                break;
            default:
                posX = posX   x;
        }
        switch (tmpY){
        case tmpY > 100:
                posY = 100;
                break;
            case tmpY < 0:
                posY = 0;
                break;
            default:
                posY = posY   y;
        }
    }
}

The error i'm getting is:

Point.java:23: error: incompatible types: boolean cannot be converted to int
            case tmpX > 100:
                      ^
Point.java:26: error: incompatible types: boolean cannot be converted to int
            case tmpX < 0:
                      ^
Point.java:33: error: incompatible types: boolean cannot be converted to int
        case tmpY > 100:
                  ^
Point.java:36: error: incompatible types: boolean cannot be converted to int
            case tmpY < 0:
                      ^
4 errors

CodePudding user response:

Instead of this switch:

switch (tmpY){
case tmpY > 100:
    posY = 100;
    break;
case tmpY < 0:
    posY = 0;
    break;
default:
    posY = posY   y;
}

use if-else:

if (tmpY > 100) {
    posY = 100;
} else if (tmpY < 0) {
    posY = 0;
} else {
    posY = posY   y;
}
  • Related