Question 5.01: Based on the ‘Icecream’ class as defined before, now create an array of Icecream type objects and get the input from the user to initialize those objects. The size of array must be at least 5.
Now, write a static method searchByCompany in the Main class of the previous implementation, which takes a String parameter representing company name and then prints all icecream’s information manufactured by that company.
Solution:
//Icecream Class
public class Icecream {
private String IcecreamType;
private String IcecreamCompany;
private double IcecreamPrice;
public Icecream() {
}
public Icecream(String IcecreamType, String IcecreamCompany, double IcecreamPrice) {
this.IcecreamType = IcecreamType;
this.IcecreamCompany = IcecreamCompany;
this.IcecreamPrice = IcecreamPrice;
}
public void setIcecreamTyepe(String icecreamtyepe){
IcecreamType = icecreamtyepe;
}
public void setIcecreamCompany(String icecreamcompany){
IcecreamCompany= icecreamcompany;
}
public void setIcecreamPrice(double icecreamPrice){
IcecreamPrice = icecreamPrice;
}
public String getIcecreamTyepe(){
return IcecreamType;
}
public String getIcecreamCompany(){
return IcecreamCompany;
}
public double getIcecreamPrice(){
return IcecreamPrice;
}
public String tostring(){
return "Icecream{"
+"IcecreamTyepe = "+IcecreamType+ '\''
+ " , IcecreamPrice = "+IcecreamPrice
+ '}';
}
boolean equals(Icecream m) {
if (IcecreamPrice == m.getIcecreamPrice()) {
return true;
}
else{
return false;
}
}
double compareto(Icecream n) {
if (IcecreamPrice<n.IcecreamPrice ) {
return 1;
}
else if (IcecreamPrice==n.IcecreamPrice ){
return 0;
}
else{
return -1;
}
}
}
// Main Class
import java.util.Scanner;
public class TESTicecream {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Icecream[] array = new Icecream[5];
for (int i = 0; i < 5; i++) {
System.out.println("Enter Company Name : ");
String a = input.nextLine();
System.out.println("Enter IceCream Tyepe : ");
String b = input.nextLine();
System.out.println("Please Enter The Price : ");
double c = input.nextDouble();
array[i] = new Icecream();
array[i].setIcecreamCompany(a);
array[i].setIcecreamTyepe(b);
array[i].setIcecreamPrice(c);
input.nextLine();
}
System.out.println("Please Enter The Company Name : ");
String com = input.nextLine();
searchbyCompany(com, array);
}
public static void searchbyCompany(String IcecreamCompany, Icecream[] array) {
for (int i = 0; i < 5; i++) {
if (array[i].getIcecreamCompany().equals(IcecreamCompany)) {
System.out.println(array[i].toString());
}
}
}
}