Reputation: 63
I want all my array data from this class to be passed to another class and I don't know how to do it. Here is my code:
public static void main(String[] args) {
String menu[] = {"", "Hotsilog", "Porksilog",
"Bangsilog", "Tapsilog", "Chicksilog"};
double priceList[] = {0, 20.00, 20.00, 20.00, 20.00, 20.00};
int quantOrder[] = new int[100];
int foodChoice[] = new int[100];
int qntty = 0;
Scanner scan = new Scanner(System.in);
System.out.printf(" %3s%14s\n", "Menu", "Price");
for (int i = 1; i <= 5; i++) {
System.out.printf("[%d] %-15s%.2f\n", i, menu[i], priceList[i]);
}
System.out.print("How many items do you want to order? ");
qntty = scan.nextInt();
for (int i = 1; i <= qntty; i++) {
System.out.println("Enter the number of your choice: ");
foodChoice[i] = scan.nextInt();
System.out.println("You choose " + menu[foodChoice[i]] + "!");
System.out.print("Quantity of order :");
quantOrder[i] = scan.nextInt();
}
}
And I want all the datas from up there to be passed to this class and compute all the prices
public class methOds {
double Price[] = new double[100];
double totalPrice = 0;
methOds() {
Price[i] = priceList[foodChoice[i]] * quantOrder[i];
totalPrice = totalPrice + Price[i];
}
}
Can some explain me how to work with it?
Thanks in advance!
Upvotes: 0
Views: 64
Reputation: 724
You need to initialize the pricelist and quantity ordered arrays to the method class and that you can pass into the constructor.
public static void main(String[] args) {
String menu[] = {"", "Hotsilog", "Porksilog",
"Bangsilog", "Tapsilog", "Chicksilog"};
double priceList[] = {0, 20.00, 20.00, 20.00, 20.00, 20.00};
int quantOrder[] = new int[100];
int foodChoice[] = new int[100];
int qntty = 0;
Scanner scan = new Scanner(System.in);
System.out.printf(" %3s%14s\n", "Menu", "Price");
for (int i = 1; i <= 5; i++) {
System.out.printf("[%d] %-15s%.2f\n", i, menu[i], priceList[i]);
}
System.out.print("How many items do you want to order? ");
qntty = scan.nextInt();
for (int i = 1; i <= qntty; i++) {
System.out.println("Enter the number of your choice: ");
foodChoice[i] = scan.nextInt();
System.out.println("You choose " + menu[foodChoice[i]] + "!");
System.out.print("Quantity of order :");
quantOrder[i] = scan.nextInt();
}
methOds method_obj = new methOds(priceList, quantOrder);
System.out.println(method_obj.totalPrice());
}
Modify your constructor and make it a parametrized one by passing both the quantOrder and foodChoice arrays so that the values could be calculated in the totalPrice method.
public class methOds {
private double Price[] = new double[100];
private double totalPrice = 0;
private int quantOrder[];
private int foodChoice[];
public methOds(quantOrder, foodChoice) {
this.quantOrder = quantOrder;
this.foodChoice = foodChoice;
}
public int totalPrice() {
//Method to calculate the total price
for (int i; i < Price.length; i++) {
Price[i] = priceList[foodChoice[i]] * quantOrder[i];
totalPrice = totalPrice + Price[i];
}
return totalPrice;
}
}
Upvotes: 1