gpt4 book ai didi

java - 我如何将这个 if-else block 转换为 switch case?(JAVA)

转载 作者:行者123 更新时间:2023-12-01 17:46:38 26 4
gpt4 key购买 nike

我一直在试图解决这个问题,但我发现在 Controller.vehicle 上切换有问题,因为它是一个 float 值。我尝试将其转换为字符串,但它不起作用并将其转换为整数,我担心它可能会失去一些精度。

    if(Controller.vehicle instanceof Boat) {
file = new File(System.getProperty("user.dir")+"/src/img/boat.png");
}
else if(Controller.vehicle instanceof Ship) {
file = new File(System.getProperty("user.dir")+"/src/img/ship.png");
}
else if(Controller.vehicle instanceof Truck) {
file = new File(System.getProperty("user.dir")+"/src/img/truck.png");
}
else if(Controller.vehicle instanceof Motorcycle) {
file = new File(System.getProperty("user.dir")+"/src/img/motorcycle.png");
}
else if(Controller.vehicle instanceof Bus) {
file = new File(System.getProperty("user.dir")+"/src/img/bus.png");
}
else if(Controller.vehicle instanceof Car) {
file = new File(System.getProperty("user.dir")+"/src/img/car.png");
}
else if(Controller.vehicle instanceof Bicycle) {
file = new File(System.getProperty("user.dir")+"/src/img/bicycle.png");
}
else if(Controller.vehicle instanceof Helicopter) {
file = new File(System.getProperty("user.dir")+"/src/img/helicopter.png");
}
else if(Controller.vehicle instanceof Airplane) {
file = new File(System.getProperty("user.dir")+"/src/img/airplane.png");
}
else if(Controller.vehicle instanceof Tram) {
file = new File(System.getProperty("user.dir")+"/src/img/tram.png");
}
else if(Controller.vehicle instanceof Train) {
file = new File(System.getProperty("user.dir")+"/src/img/train.png");
}

最佳答案

使用多个instanceof操作通常意味着你的设计很糟糕。

无论车辆类是什么,它都应该有一个抽象的 getImageFile() 方法,并且它的每个子类(船舶、卡车等)都应该重写该方法以获得正确的图像。所以你上面的方法将只包含一行:

  file = Controller.vehicle.getImageFile();

这将适应其中一些图像文件可能是 .jpg、一些可能是 .png 等的可能性。

关于java - 我如何将这个 if-else block 转换为 switch case?(JAVA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54448129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com