I am doing an assignment for school in which I have to use examples of instanceof for casting. Currently,I have the following code
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");
}
}
}
and I try to check after buying a ticket if I should call the print function thats used by the "kid" class by trying to check if visitor has become instanceof kid
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
For some reason,I get the following error.
Inconvertible types; cannot cast 'com.projects.Visitor' to 'com.projects.Visitor.kid'
and also
Cannot resolve method 'print' in 'Visitor'
I checked around but could not find/understand a solution since I am new to java
Any help is appreciated :)