0

Beginner here, but for the life of me I couldn't find an answer to this question after searching and trying to figure it out for myself.

I have a very simple app calculating tips, and I'm trying to stop the app crashing when only a decimal place is put into the editText.

public void calculate() {
        float result = 0.0f;
        float totalBillResult;

        if(!enteredAmount.getText().toString().equals("")) {
            NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.getDefault());

            if(!enteredAmount.getText().toString().equals(".")){
                Toast.makeText(MainActivity.this, "Please enter a bill amount", Toast.LENGTH_SHORT);
            }

            enteredBillFloat = Float.parseFloat(enteredAmount.getText().toString());
            result = enteredBillFloat*seekBarPercent /100;
            calculatedTip.setText("Your tip will be " + String.valueOf(numberFormat.format(result)));
            totalBillResult = enteredBillFloat+result;
            totalBill.setText("Total bill: " + String.valueOf(numberFormat.format(totalBillResult)));

        }else {
            Toast.makeText(MainActivity.this, "Please enter a bill amount", Toast.LENGTH_LONG).show();
        }

I have tried putting another if statement within the above text to get another toast to show if only a decimal is inputted, and while it doesn't cause any errors it also doesn't do anything, and the app just shuts down when I click to calculate.

  if(enteredAmount.getText().toString() == (".")) {
            calculatedTip.setText("Please enter a number.");
        }

I have also tried putting this in the main body of the code to no avail. The logcat is telling me its a NumberFormatException, but after reading this: https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html that was on another post I am none the wiser on how to fix this.

Any ideas would be appreciated, and I will edit to add more code if needed Thanks

  • insert as first if-Statement: `if(enteredAmount.getText().toString() == (".")) { calculatedTip.setText("Please enter a number."); return; }` so that Your app leaves the method – GGK stands for Ukraine Apr 29 '20 at 14:35
  • @GGK thanks for the reply, but I'm not entirely sure where I am meant to put this? I have inserted it in the public void calculate method in the original question, and I have tried inserting it into the protected void onCreate, but neither have any effect within the app when only a decimal is inserted, it still crashes. – Stuart Wright Apr 29 '20 at 15:04
  • Your problem is based in the code and not in android. In onCreate() start your calculate() method. First line in this method is above mentione `if`statement. Please use some coding practice in java bevor starting android...makes it easier for you – GGK stands for Ukraine Apr 29 '20 at 20:02

0 Answers0