メインクラスで以下のコードを走らせた時にエラー(NullPointerException)が出てしまいます。
その解消としてPizzaOrderクラスのcalcTotal()メソッドの中でnullを感知したら0をトータルに足すようにしてエラーの解消を図りましたがうまくいきませんでした。
なにが問題でしょうか。
double total = order.calcTotal();
PizzaOrder class
package Pra3_4; public class PizzaOrder { private Pizza[] pizzas = new Pizza[3]; /* public PizzaOrder(Pizza[] pizzas) { this.pizzas = pizzas; } */ public void setPizzas(Pizza newPizza, int index) { pizzas[index] = newPizza; } public Pizza[] getPizzas() { return pizzas; } public double calcTotal() { double total = 0.0; for(int i = 0; i < pizzas.length; i++) { if(pizzas[i] == null) total += 0; total += pizzas[i].calcCost(); } return total; } @Override public String toString() { String orderlist = ""; for(int i = 0; i < pizzas.length; i++) { orderlist += pizzas[i]; } return orderlist; } /* public int getNumPizzas() { } */ }
Main class
package Pra3_4; import java.util.Arrays; /* * Using your pizza code that you previously completed last week. * Create a PizzaOrder class that allows up to three pizzas * to be saved in an order. * Each pizza saved should be a Pizza object * (you have already written this). * In addition to appropriate instance variables and constructors, * add the following methods: * public void setNumPizzas(int numPizzas) * - sets the number of pizzas in the order, * numPizzas must be between 1 and 3. * • public void setPizza1(Pizza pizza1) - set pizza 1 * • public void setPizza2(Pizza pizza2) - set pizza 2 * • public void setPizza3(Pizza pizza3) - set pizza 3 * • public double calcTotal() - returns the total cost of the order * Write a main method to test the class. * The setPizza2 and setPizza3 methods will be used * only if there are two or three pizzas in the order, respectively. * Sample code illustrating the methods is shown below. * Note the first three lines are incomplete. * You must complete them on your own. * Pizza pizza1 = //code to create a large pizza, 1 cheese 1 ham * Pizza pizza2 = //code to create a medium pizza, 2 cheese, 2 pepperoni * PizzaOrder order = //Code to create an order * order.setNumPizzas(2); // 2 pizzas in the order * order.setPizza1(pizza1); //set first pizza * order.setPizza2(pizza2);//set second pizza * double total = order.calcTotal(); //should be 18+20 = 38 */ public class Main { public static void main(String[] args) { Pizza pizza1 = new Pizza("large", 1, 0, 1); Pizza pizza2 = new Pizza("medium", 2, 2, 0); PizzaOrder order = new PizzaOrder(); order.setPizzas(pizza1,2); order.setPizzas(pizza2,0); Pizza[] list2 = order.getPizzas(); System.out.println(Arrays.toString(list2)); for(int i = 0; i < list2.length; i++) { System.out.println(list2[i]); } double total = order.calcTotal(); System.out.printf("Pizza Order total cost $%.2f\n", total); } }
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/04/06 08:15
2021/04/06 09:30