在计算数字时检查EditText是否为空
我正在尝试构建一个年龄计算器应用程序。 当我没有输入编辑EditTexts
一个数字,然后点击计算Button
,我的应用程序崩溃了! “应用程序已停止”并单击照片
我试着设置yearbirth.isEmpty() || yearbirth.equals("") || yearbirth == null
yearbirth.isEmpty() || yearbirth.equals("") || yearbirth == null
yearbirth.isEmpty() || yearbirth.equals("") || yearbirth == null
,但没有任何工作。
码:-
class MainActivity : AppCompatActivity() { var yearage:Int?= null var monthage:Int?= null var dayage:Int?= null @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) buGetAge.setOnClickListener({ val year= Calendar.getInstance().get(Calendar.YEAR) val month= Calendar.getInstance().get(Calendar.MONTH) val day= Calendar.getInstance().get(Calendar.DAY_OF_MONTH) var yearage = year - Integer.parseInt(yearbirth.text.toString()) -1 val monthage:Int? val dayage:Int? if (yearbirth== null) { Toast.makeText(this, "You have to enter your year berth", Toast.LENGTH_LONG).show() } else { if (month < Integer.parseInt(monthbirth.text.toString())){ monthage=(Integer.parseInt(monthbirth.text.toString())- month- 12)* -1 }else if (month > Integer.parseInt(monthbirth.text.toString())) { yearage=year- Integer.parseInt(yearbirth.text.toString()) monthage= (Integer.parseInt(monthbirth.text.toString())- month)* -1 }else { yearage=year- Integer.parseInt(yearbirth.text.toString()) monthage=0 } if (day < Integer.parseInt(daybirth.text.toString())){ dayage= (Integer.parseInt(daybirth.text.toString())- day- 30)* -1 }else if (day > Integer.parseInt(daybirth.text.toString())){ dayage= day- Integer.parseInt(daybirth.text.toString()) }else { dayage=0 } val a= (yearage* 12)+ monthage val b= (a * 30)+ dayage val ageinyears= "$yearage years" val ageinmonths= "$a months" val ageindays= "$b days" txtshow.text = "Your age is $yearage years, $monthage months and $dayage days" txtshow2.text = "\nYOUR AGE:\nin years:\n\nin months:\n\nin days:" txtshow3.text = "\n\n$ageinyears \n\n$ageinmonths \n\n $ageindays " this.yearage=yearage this.monthage=monthage this.dayage=dayage } }) } }
您可以检查像这样的空Input
:
newString = Integer.toString(yearbirth).trim(); if (newString.matches("")) { Toast.makeText(this, "EditText is empty", Toast.LENGTH_SHORT).show(); return; }
验证yearbirth.text.toString()
在尝试将其解析为整数之前(以及它是否为有效整数)之前不是空的。
为了达到这个目的,把你在代码中显示的那一行:
var yearage = year - Integer.parseInt(yearbirth.text.toString()) -1
if
验证输入是有效的,如下所示:
if(yearbirth.text.toString().matches(Regex("\\d+"))) var yearage = year - Integer.parseInt(yearbirth.text.toString()) -1