how to use the instanceof method correctly
The task is given: Create a static printMagazines(Printable[] printable) method in the Magazine class that outputs only the names of the magazines to the console. Create a static method printBooks (Printable[] printable) in the Book class, which outputs only the names of books to the console. We use the instanceof operator. I wrote the method, but its execution leads to an error. Please help:) Code:
public class Main {
public static void main(String[] args) {
Printable[] test=new Printable[3];
test[0]=new Book();
test[1]=new Magazine("keke");
test[2]=new Book();
int k=0;
for (Printable i:test){
test[k].print();
k++;
}
**if (test[k] instanceof Magazine){
int l=0;
((Magazine) test[k]).printMagazines(test);
k++;
}**
}}
public interface Printable {
Printable print();
}
public class Book implements Printable {
String name;
@Override
public Printable print() {
System.out.println("1");
return null;
}
public void printBooks(Printable[] printable){
Printable b=print();
System.out.println(b);
}
}
public class Magazine implements Printable {
String name;
Magazine(String name){
this.name=name;
}
@Override
public Printable print() {
System.out.println("2");
return null;
}
public void printMagazines(Printable[] printable){
System.out.println(name);
}
}
Mistake: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Main.main(Main.java:19)
Thank you in advance!
0
1 answers
public class Magazine implements Printable {
...
public static void printMagazines(Printable[] printables) {
for (Printable p: printables) {
if (p instanceof Magazine)
p.print();
}
}
}
Magazine.printMagazines(test);
1
Author: Igor, 2020-11-05 18:57:17