微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在java中使用instanceof“无法转换”错误

如何解决在java中使用instanceof“无法转换”错误

我正在为学校做一项作业,我必须使用 instanceof 的示例进行投射。 目前,我有以下代码

public class Visitor implements Actions{
    public Object buyTicket(Object visitor1){
        System.out.println("\nInput your age:");
        Scanner scanner = new Scanner(system.in);
        int age = Integer.parseInt(scanner.nextLine());
        System.out.println("Input your budget:");
        int cash = Integer.parseInt(scanner.nextLine());
        if (age <18 && cash >=5){
            visitor1=new kid();
            System.out.println("You have bought a ticket");
        }
        else if(age >=18 && cash >=10){
            System.out.println("You have bought a ticket");
        }
        else{
            System.out.println("Not enough funds to buy a ticket");
        }
        return visitor1;
    }
    public static class kid{
        void print(){
            System.out.println("Legal guardian required for entry");
        }
    }
}

并且我在买票后尝试检查是否应该通过尝试检查访问者是否已成为孩子的实例来调用“孩子”类使用的打印功能

    static void VisitorActions(){
        Visitor visitor = new Visitor();
        label3:
        while (true){
            Scanner scanner = new Scanner(system.in);
            String userChoice=scanner.nextLine();
            switch (userChoice){
                case "1":
                    visitor.buyTicket(visitor);
                    if (visitor instanceof Visitor.kid){
                        visitor.print();
                    }
                    break;
            //code continues to other cases

出于某种原因,我收到以下错误

不可转换的类型;无法将“com.projects.Visitor”转换为“com.projects.Visitor.kid”

还有

无法解析“访问者”中的方法“打印”

我查了一下,但找不到/理解解决方案,因为我是 Java 新手

感谢任何帮助:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。