我想做一個測驗分數計算應用程式。我有一些問題。如何防止在edittext中輸入大于20的值,如果edittext為空,在edittext中寫入0并計算0值。當應用程式運行時,它會計算分數,但當 Edittext 輸入 null 時,應用程式會關閉。我想如果edittext為空,應用程式將空值設定為0并計算分數。這是我的應用程式的影像:1:https : //i.stack.imgur.com/efn9H.png
這是我正在使用的代碼:
public class MainActivity extends AppCompatActivity {
EditText editText1,editText2,editText3;
private Button calculate;
TextView textView1;
double c=0.0,x;
int a=0,b=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1=findViewById(R.id.correct_answer);
editText2=findViewById(R.id.false_answer);
editText3=findViewById(R.id.turnet);
textView1=findViewById(R.id.hesap);
calculate=findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
a=Integer.parseInt(editText1.getText().toString());
b=Integer.parseInt(editText2.getText().toString());
x=a b;
if (x<=20){
if (editText1.getText().toString().length()==0)
{
a=0;
Toast.makeText(getApplicationContext(),"Correct Answers must be max:20 .", Toast.LENGTH_LONG).show();
}
else{
a=Integer.parseInt(editText1.getText().toString());
}
if (editText2.getText().toString().length()==0)
{
Toast.makeText(getApplicationContext(),"False Answers must be max:20.", Toast.LENGTH_LONG).show();
b=0;
editText2.setText(0);
}
double c = a - (b / 3);
double result=((200.004394) (c*3.44603333));
editText3.setText(Double.toString(c));
textView1.setText("Your Score: " Double.toString(result));
}
else{
Toast.makeText(getApplicationContext(),"All English questions dont greater than 20.", Toast.LENGTH_LONG).show();
}
};});}}
uj5u.com熱心網友回復:
您可以使用TextWatcher。撰寫一個 TextWatcher,如果它大于 20,則將其更改為 20,如果EditText's 的文本為空,則將其設定為 0
uj5u.com熱心網友回復:
這段代碼有問題:
a=Integer.parseInt(editText1.getText().toString());
b=Integer.parseInt(editText2.getText().toString());
當您的編輯文本之一為空時,將引發錯誤,因為 Integer.parseInt 不能接受空字串。所以用這個:
a = 0;
b = 0;
if (editText1.getText().toString() != ""){
a=Integer.parseInt(editText1.getText().toString());
}
if(editText2.getText().toString() != ""){
b=Integer.parseInt(editText2.getText().toString());
}
x = a b
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/408437.html
標籤:
