简体   繁体   English

object 转换期间线程“main”错误中的异常 [java.lang.ClassCastException] - 如何解决转换问题?

[英]Exception in thread "main" error during object casting [java.lang.ClassCastException] - How to fix casting issue?

I am writing a program which consists of several classes (2 superclasses and a couple subclasses for each).我正在编写一个由多个类组成的程序(每个类有 2 个超类和几个子类)。 Within my driver file, I created two arrays: the first array contains objects from two completely separate classes (unrelated to each, no parent/subclass relation), and the second array contains objects that are from one of my superclass and its subclasses.在我的驱动程序文件中,我创建了两个 arrays:第一个数组包含来自两个完全独立的类的对象(与每个类无关,没有父/子类关系),第二个数组包含来自我的一个超类及其子类的对象。

While writing and testing out the method which finds and prints the cheapest and most expensive objects from each of the arrays, I encountered an error which is related to my casting which I had to do to make the method work.在编写和测试从每个 arrays 中查找和打印最便宜和最昂贵的对象的方法时,我遇到了一个与我的转换相关的错误,我必须这样做才能使该方法起作用。 I've included shorter versions of my various classes below:我在下面包含了我的各种课程的较短版本:

//First superclass
package Plane;
public class Plane {
    
    
     private String brand;
     private double price; 
     private int horsepower;
    
     
    public Plane() {
        brand = "test";
        price = 50000.99; 
        horsepower = 500;
    }
    
    public Plane(String planeBrand, double planePrice, int planePower) {
        this.brand = planeBrand;
        this.price = planePrice;
        this.horsepower = planePower;
    }
    
    public String getBrand() {
        return this.brand;
    }
    public void setBrand(String planeBrand) {
        this.brand = planeBrand;
    }
    
    public double getPrice() {
        return this.price;
    }
    
    public void setPrice(double planePrice) {
        this.price = planePrice;
    }
    
    public int getPower() {
        return this.horsepower;
    }
    
    public void setPower(int planePower) {
        this.horsepower = planePower;
    }
    
    public Airplane(Plane plane) {
        this.brand = plane.getBrand();
        this.price = plane.getPrice();
        this.horsepower = plane.getPower();
    }
    
    public String toString() {
        return "The airplane is manufactured by " + this.brand + " and costs $" + this.price + ". It has " + this.horsepower + " horsepower.";
    }

    public boolean equals(Plane plane) {
        if (!(plane instanceof Plane) || plane == null) {
                return false;
            } else if (this.brand != plane.getBrand() || this.price != plane.getPrice() || this.horsepower != plane.getPower()) {
                    return false;
                } else {
                    return true;
                }
            }
        }
//Second superclass
package Boat;
public class Boat {

    private double weight;
    private double price;
    
    public UAV() {
        weight = 3949.5;
        price = 64000;
    }
    
    public UAV(double boatWeight, double boatPrice) {
        weight = boatWeight;
        price = boatPrice;
    }
    
    public double getWeight() {
        return this.weight;
    }
    
    public void setWeight(double boatWeight) {
        this.weight = boatWeight;
    }
    
    public double getPrice() {
        return this.price;
    }

    public void setPrice(double boatPrice) {
        this.price = boatPrice;
    }
    
    public Boat(Boat boat) {
        this.weight = boat.getWeight();
        this.price = boat.getPrice();
    }
    
    public String toString() {
        return "This boat weighs " + this.getWeight() + "kg and costs $" + this.getPrice() + ".";
    }
    
    public boolean equals(Boat boat) {
        if (!(boat instanceof Boat) || boat == null) {
            return false;
        } else if (this.price != boat.price || this.weight != boat.weight) {
            return false;
        } else {
            return true;
        }
    }
    
}
//Driver file that produces the error
public class Main {

    public static void main(String[] args) {
        
       Object[] mixedObjects = new Object[8];
        
        mixedObjects[0] = new Plane();
        mixedObjects[1] = new Plane();
        mixedObjects[2] = new Helicopter();
        mixedObjects[3] = new Helicopter();
        mixedObjects[4] = new Drone();
        mixedObjects[5] = new Drone();
        mixedObjects[6] = new Boat();
        mixedObjects[7] = new Boat();
        
        
        Object[] planeObjects = new Object[6];
        
        airplaneObjects[0] = new Plane();
        airplaneObjects[1] = new Plane();
        airplaneObjects[2] = new Helicopter();
        airplaneObjects[3] = new Helicopter();
        airplaneObjects[4] = new Drone();
        airplaneObjects[5] = new Drone();
        
        findLeastAndMostExpensiveBoat(mixedObjects);
        findLeastAndMostExpensiveBoat(planeObjects);
        //The top line is line 91 (SEE ERROR MESSAGE)

public static void findLeastAndMostExpensiveBoat(Object[] mixedObjects) {
        if(mixedObjects.length == 1 && mixedObjects[0] instanceof Boat) {
            System.out.println(mixedObjects[0] + " is the most and least expensive.");
        }
        else if(mixedObjects.length == 0) {
            System.out.println("Empty array");
        }
        else if (mixedObjects.length == 1 && !(mixedObjects[0] instanceof Boat)){
            System.out.println("No UAV object detected.");
        }
        else {
            int max = 0;
            int min = 0;
            //Maximum
            for(int i = 0 ; i< mixedObjects.length; i++) {
                if(mixedObjects[i] instanceof Boat) {
                    System.out.println(mixedObjects[i].getClass());
            //The following line is line 157 (SEE ERROR MESSAGE)
                    if(((Boat)mixedObjects[i]).getPrice() >        ((Boat)mixedObjects[max]).getPrice()) {
                        max = i;
                    }
                } else {
                    System.out.println("No Boat object detected.");
                }
            }
            //Mininmum
            for(int i = 0 ; i< mixedObjects.length; i++) {
                if(mixedObjects[i] instanceof Boat) {
                    if(((Boat)mixedObjects[i]).getPrice() < ((Boat)mixedObjects[min]).getPrice()) {
                        min = i;
                    }
                } else {
                    System.out.println("No Boat object detected.");
                }
            }
        } 
    }
} 

The findLeastAndMostExpensiveBoat method basically checks any array for the most expensive and cheapest boat. findLeastAndMostExpensiveBoat方法基本上检查任何数组中最昂贵和最便宜的船。 If no boats are present, then it prints a message saying so.如果没有船只存在,那么它会打印一条消息说明这一点。 The error code I get when I run my code is:我运行代码时得到的错误代码是:

Exception in thread "main" java.lang.ClassCastException: class Plane.Plane cannot be cast to class Boat.Boat (Plane.Plane and Boat.Boat are in unnamed module of loader 'app')
    at Main.findLeastAndMostExpensiveBoat(Main.java:157)
    at Main.main(Main.java:91)

Line 91 as per error message is: findLeastAndMostExpensiveBoat(planeObjects);根据错误消息,第 91 行是: findLeastAndMostExpensiveBoat(planeObjects);

Line 157 as per error message is: if(((Boat)mixedObjects[i]).getPrice() > ((Boat)mixedObjects[max]).getPrice())根据错误消息,第 157 行是: if(((Boat)mixedObjects[i]).getPrice() > ((Boat)mixedObjects[max]).getPrice())

Where exactly did I go wrong with my code?我的代码 go 到底哪里错了? Is my cast syntax wrong, or is there a deeper issue I need to resolve?我的转换语法是错误的,还是我需要解决更深层次的问题?

You are checking whether an object is instance of Boat by if(mixedObjects[i] instanceof Boat) but you don't certainly know that mixedObjects[max] is type of Boat .您正在通过if(mixedObjects[i] instanceof Boat) Boat object 是否是 Boat 的实例,但您当然不知道mixedObjects[max]Boat的类型。 The same is true for the min case.最小情况也是如此。 You may add an extra condition like mixedObjects[max] instanceof Boat too.您也可以添加一个额外的条件,例如mixedObjects[max] instanceof Boat

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 线程“ main”中的异常java.lang.ClassCastException: - Exception in thread “main” java.lang.ClassCastException: java.lang.ClassCastException:将对象强制转换为其父对象 - java.lang.ClassCastException: casting an object, to his parent 线程“ main”中的异常java.lang.ClassCastException:[Ljava.lang.Object; 无法转换为[B - Exception in thread “main” java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [B 线程“ main”中的异常java.lang.ClassCastException:[Ljava.lang.Object; 无法转换为模型。AdminPopulate - Exception in thread “main” java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to model.AdminPopulate 线程“ main”中的异常java.lang.ClassCastException:具有优先级队列和比较器 - Exception in thread “main” java.lang.ClassCastException: with priority queue and comparator 线程“主”java.lang.ClassCastException 中的异常:java.util.LinkedHashMap 无法转换为自定义 Object - Exception in thread “main” java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to Custom Object 每当我在 java 中使用 treeset.add() 方法时,线程“主”java.lang.ClassCastException 中的错误异常 - Error Exception in thread “main” java.lang.ClassCastException whenever I use treeset .add() method in java Java泛型MergeSort,线程“主”中的异常java.lang.ClassCastException错误 - Java Generics MergeSort, exception in thread “main” java.lang.ClassCastException error 强制转换java.lang.reflect.Method.invoke的对象结果时,java.lang.ClassCastException - java.lang.ClassCastException when casting Object-result of java.lang.reflect.Method.invoke 错误:“线程中的异常”main“java.lang.ClassCastException:manycard.Main$Card 无法转换为 java.lang.Comparable” - Error: “Exception in thread ”main“ java.lang.ClassCastException: manycard.Main$Card cannot be cast to java.lang.Comparable”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM