0

I have a simple screen with two EditText Boxes and 1 button. I want users to be able to enter various integers into the boxes and the program will perform different operations based on the specific number entered into the box. I'm trying to have them only enter one number at a time but the code wont seem to execute unless both boxes have something in them. And I'm having the if statements check for nulls on the respective boxes before executing to determine which piece of code to execute.

 public void button(View view) {

    double x, y;
    EditText freq1 = findViewById(R.id.freq1);
    EditText freq2 = findViewById(R.id.freq2);
    TextView str1 = findViewById(R.id.freqanswer);
    TextView str2 = findViewById(R.id.injVolt);
    TextView error1 = findViewById(R.id.error1);

    String strf1, strf2;

    strf1 = freq1.getText().toString();
    strf2 = freq2.getText().toString();

    try {

        f1 = Double.parseDouble(strf1);
        f2 = Double.parseDouble(strf2);

        if ((f1 >= 225) & (f1 <= 312) & (strf1.isEmpty())) {

            x = f1 + 20.6;
            y = x / 4;
            str1.setText(String.format("%.3f", y));

        }

    }
    catch (Exception e){
        error1.setText("splat");
    }
    finally {
        InputMethodManager input = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        input.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

I included only 1 formula for the sake of brevity, but I'm going to be putting about 6 if statements, checking for number ranges and nulls on this button and I just need it to run with one box being empty. I know the formula works by having play with various outputs, it just won't run with the strf1.isEmpty(). Something has to be in that second box for the formula to execute. Would appreciate any help

  • 2
    A empty edittext will return an empty string ```""``` not ```null```, your problem is that Double.parseDouble("") will imediately trhow a Exception, you must check before parsing – Marcos Vasconcelos Jul 22 '18 at 19:40
  • what do you mean by `I'm trying to have them only enter one number at a time ` what do you want to execute by taking only single value ..state that clearly because based on your operation error checking code might change – Achy97 Jul 22 '18 at 19:45

1 Answers1

0

I think you should check before assigning:

if(strf1.isEmpty()){strf1="0";} //if assuming zero does not change the formula's output 
if(strf2.isEmpty()){strf2="0";}

f1 = Double.parseDouble(strf1);
f2 = Double.parseDouble(strf2);

this way you are assured of a default value.