Exception in thread "main" java.lang.Error: Unresolved compilation problems: Type mismatch: cannot convert from Rock to Ball Incompatible conditional operand types Ball and Rock at Driver.main(Driver.java:23) The code runs fines for Football and Baseball classes but not for the rock class. Rock implements an interface called Tossable (Which both Football and Baseball are also implementing). Furthermore, Football and Baseball both extend the Ball class. Thank you!
import java.util.Scanner;
import java.util.*;
public class Driver {
public static void main(String[] args){
int n;
int x;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
n=sc.nextInt();
Ball[] ball = new Ball[n];
for(int i=0; i<n; i++){
System.out.print("Enter the brand name of the ball: ");
String brandName = sc.next();
System.out.print("Enter the type of ball (case sensitive): ");
String type = sc.next();
if(type.equals("Baseball")){
ball[i] = new Baseball(brandName);
}
else if(type.equals("Football")){
ball[i] = new Football(brandName);
}
else if (type.equals("Rock")){
ball[i] = new Rock();
}
else{
System.out.println("Invalid type of ball");
i--;
}
}
for(int i=0; i<n; i++){
int count = 0;
if(ball[i] instanceof Rock){
count++;
}
System.out.println("There are " + count + " Rocks in the array");
}
for(int i=0; i<n; i++){
if(ball[i] instanceof Football){
System.out.println("Football:");
ball[i].bounce();
ball[i].toss();
}
else if(ball[i] instanceof Baseball){
System.out.println("Baseball:");
ball[i].toss();
}
}
}
}