在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 (将#修改为@)