Q1:运行此命令时,我得到了nullpointerexception。 当我在Hamburger中评论AdditionalItems()并将其放在HealthyBurger中时,它运行良好,所以我真的不知道我该怎么做。
Q2:有什么更好的方法让extraItems()不再重复4次?
public class Hamburger {
public Hamburger(String breadType, String meatType, int price){
this.breadType = breadType;
this.meat = meatType;
this.price = price;
additionalItems();
}
public void additionalItems(){
System.out.println("Would you like lettuce/carrot/cheese/tomato? (y/n)x4");
String s = scanner.next();
if(s.equalsIgnoreCase("y")){
this.setLettuce(true);
this.setPrice(price+2);
System.out.println("Lettuce added! Current Price: " + this.price);
} else { System.out.println("did not add ");
}
......
-----------------------------------------------------------------------
package com.company;
import java.util.Scanner;
public class HealthyBurger extends Hamburger{
private boolean salad;
private boolean corn;
Scanner scanner2 = new Scanner(System.in);
public HealthyBurger(){
super("brown roll", "red", 7);
// this.additionalItems();
}
public void additionalItems(){
System.out.println("would you like salad to your healthyburger? y/n");
String x2 = scanner2.next();
if(x2.equalsIgnoreCase("y")){
this.setSalad(true);
System.out.println("Added salad to your burger!");
this.setPrice(this.getPrice() + 2);
}else {
System.out.println("did not add salad");
}
........
}