0

我想计算它的两位数除法之外,用户使用编辑框输入两个数字,当用户将一个编辑文本留空时,他会发出一条错误消息,而不会破坏我尝试使用的应用程序,但应用程序总是压碎

public class MainActivity extends AppCompatActivity {
    private EditText a1,a2;
    private Button s;
    private TextView d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        a1=findViewById( R.id.editTextTextPersonName );
        a2=findViewById( R.id.editTextTextPersonName2 );
        s=findViewById( R.id.button );
        d=findViewById( R.id.textView );
        s.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float aa = Float.parseFloat( a1.getText().toString() );
                float ss = Float.parseFloat( a2.getText().toString() );
                float f = aa / ss;
                if(a1.getText().toString()==null){
                    a1.setError( "n1 is required" );
                    a1.requestFocus();
                }else if(a2.getText().toString()==null){
                    a2.setError( "n1 is required" );
                    a2.requestFocus();
                }else {
                    d.setText( (int) f );
                }
            }
        });
    }
}
4

2 回答 2

0

如果应用程序崩溃,请检查日志窗口中的错误或异常类型。如果日志窗口显示一些 nullPointerException(),则使用它们各自的类型对成员 a1、a2、s、d 进行类型转换。即...(EditText), (TextView),(Button)。如果没有显示此异常,也请养成对类型转换成员的习惯,以避免任何麻烦。

If after that also there comes some issue than,make these changes over the code ---------------------------------->
if(TextUtils.isEmpty(a1.getText().toString()))
a1.setError("n1 is required" );
else if(TextUtils.isEmpty(a1.getText().toString())){
                    a2.setError( "n1 is required" );
                    a2.requestFocus();
                }else {
                    d.setText( (int) f );
                }
于 2021-03-15T15:10:51.900 回答
0

您只需要检查编辑文本是否为空。

试试下面的代码

String FirstEdit = a1.getText().toString();
String SecondEdit = a2.getText().toString();

if (TextUtils.isEmpty(FirstEdit) || TextUtils.isEmpty(SecondEdit))
{
//Your Message
}
于 2021-03-15T15:00:17.500 回答