I am trying to use IcecreamArray[] in the method searchByCompany() to print out ice cream information by its company name, but it is giving me an error that the array does not exist.
Error: Create local variable IcecreamArray. Also, how can I make my code more efficient?
public class MainIcecream {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Icecream[] IcecreamArray = new Icecream[5];
for (int i = 0; i < 5; i++) {
IcecreamArray[i] = new Icecream();
System.out.println("Enter Icecream type " + i + " : ");
IcecreamArray[i].setIcecreamType(sc.next());
System.out.println("Enter Icecream Company " + i + " : ");
IcecreamArray[i].setIcecreamCompany(sc.next());
System.out.println("Enter Icecream Price " + i + " : ");
IcecreamArray[i].setIcecreamPrice(sc.nextDouble());
}
public static void searchByCompany(String s){
for (int i = 0; i < 5; i++) {
if(s.equals(IcecreamArray[i].getIcecreamCompany())){
System.out.println(IcecreamArray[i].getIcecreamType());
System.out.println(IcecreamArray[i].getIcecreamCompany());
System.out.println(IcecreamArray[i].getIcecreamPrice());
}
}
}
public static class Icecream {
private String icecreamType;
private String icecreamCompany;
private double icecreamPrice;
public String toString(){
String str , t , c;
double p;
t = icecreamType;
c = icecreamCompany;
p = icecreamPrice;
str = "Icecream type: " + t + "\nManufacturer: " + c + "\nPrice: " + p;
return str;
}
public void setIcecreamType(String t) {
icecreamType = t;
}
public void setIcecreamCompany(String c){
icecreamCompany = c;
}
public void setIcecreamPrice(double p){
icecreamPrice = p;
}
String getIcecreamType(){
return icecreamType;
}
String getIcecreamCompany(){
return icecreamCompany;
}
double getIcecreamPrice(){
return icecreamPrice;
}
}
}