我的try catch函数无法按预期工作

时间:2018-12-29 07:28:20

标签: java android if-statement try-catch

我的程序应该采用给定的值并用它找到另一个值。但是,我的try catch语句似乎不起作用。它永远不会执行程序最重要的部分的if语句。当您输入两个值时,第三个值确实起作用。预先感谢。

        public void calculate(View view) {
    EditText length_find = findViewById(R.id.feet);
    EditText pounds_find = findViewById(R.id.pounds);

    try {
        //int length_int = Integer.parseInt(length_find.getText().toString());
        //int pounds_int = Integer.parseInt(pounds_find.getText().toString());

        double d = .29;
        //double length = length_int;
        //double pounds = pounds_int;
        double w = 24.5 / 12;
        double h = .002 / 12;

        //This Calculates if Pounds are given
        if ((length_find).getText().toString().trim().length() == 0){
            Toast.makeText(MainActivity.this, "Given Pounds", LENGTH_LONG).show();
            int pounds_int = Integer.parseInt(pounds_find.getText().toString());
            double pounds = pounds_int;
            double v = pounds / d;
            double length = v / w / h;
            final TextView mTextView = (TextView) findViewById(R.id.length_show);
            mTextView.setText((int) length);
        }


        //This Calculates if Length is given
        if ((pounds_find).getText().toString().trim().length() == 0){
          Toast.makeText(MainActivity.this, "Given Length", LENGTH_LONG).show();
          int lenght_int = Integer.parseInt(length_find.getText().toString());
          double length = lenght_int;
          double v = length * w * h;
          double answer_pounds = v * d;
          final TextView mTextView = (TextView) findViewById(R.id.pound_show);
          mTextView.setText((int) answer_pounds);
        }
        if((pounds_find).getText().toString().trim().length() > 0 && (length_find).getText().toString().trim().length() > 0){
            Toast.makeText(MainActivity.this, "Whata hell you need me for mate!", LENGTH_LONG).show();
        }

    }
    catch(Exception ex) {
            Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
        }

    }

1 个答案:

答案 0 :(得分:1)

据我了解,

(pounds_find).getText().toString().trim().length() <= 0

(length_find).getText().toString().trim().length() <= 0

仅在用户未输入任何内容时为true。如果有,则按预期执行第三个“如果”。但是,当用户没有输入任何内容时

int length_int = Integer.parseInt(length_find.getText().toString());
int pounds_int = Integer.parseInt(pounds_find.getText().toString());

无法完成。因为它是空的。我认为情况就是这样。如果不是,请通知我。如果我错了,抱歉。这就是我从这里了解到的。如果您可以调试并针对场景或异常(如果有的话)进行具体说明,那将更有帮助