使用空 EditText 提交订单时阻止应用程序崩溃

Stop app from crashing when submitting order with empty EditText

我最近开始学习编程,正在编写一个咖啡订购应用程序。我有一个 "price" 字段,您可以在其中输入一杯咖啡的基本价格和一些其他选项。现在,如果我在价格字段为空时单击 "Order" 按钮,应用程序就会崩溃。我试图从关于是否可以在 EditText 中同时拥有默认值和提示的问题中添加代码行。 这是计算价格的方法的代码,复选框是咖啡浇头的复选框,功能正常:

// Calculates the price
private int calculatePrice(int quantity) {
    // Price per cup in field
    EditText pricePerCupF = (EditText) findViewById(R.id.basic_price);
    boolean whippedChecked = ((CheckBox) findViewById(R.id.whipped_cream)).isChecked();
    boolean chocolateChecked = ((CheckBox) findViewById(R.id.chocolate)).isChecked();
    int pricePerCup = Integer.parseInt(pricePerCupF.getText().toString());
    if (whippedChecked) {
        pricePerCup += 1;
    }
    if (chocolateChecked) {
        pricePerCup += 1;
    }
    if (pricePerCupF.getText().toString().equals("")) {
        return 0;
    }
    else {

        int price = pricePerCup * quantity;
        return price;
    }

谢谢!

 if (pricePerCupF.getText().toString().equals("")) {
        return 0;
 }

之前

 int pricePerCup = Integer.parseInt(pricePerCupF.getText().toString());

如果字段为空,这样您可以在出现任何解析/转换错误之前退出函数。