java - How get variable type? -
in application have 2 textfield , 1 submit. app calculate integer value in textfiels. if put there text - have error. how can check text field int , how show message if thare no integers. try:
edittext num1text=(edittext)findviewbyid(r.id.num1text); edittext num2text=(edittext)findviewbyid(r.id.num2text); float num1=float.parsefloat(num1text.gettext().tostring()); float num2=float.parsefloat(num2text.gettext().tostring()); if (num1 instanceof float && num2 instanceof float) { float answ = (num1 * num2) / 100; textview answer=(textview)findviewbyid(r.id.ans); answer.settext(answ); }else answer.settext("message"); but app still don't show message in else case.
as others commented, can use regular expression check contents of input field before start converting them. recommendation, should scrub user inputs before use.
if don't, or can't: float.parsefloat() operation throws numberformatexception if input cannot converted. need use try...catch construct avoid this.
try { float num1=float.parsefloat(num1text.gettext().tostring()); float num2=float.parsefloat(num2text.gettext().tostring()); float answ = (num1 * num2) / 100; textview answer=(textview)findviewbyid(r.id.ans); answer.settext(answ); } catch (numberformatexception e) { textview answer=(textview)findviewbyid(r.id.ans); answer.settext("message"); } furthermore, can use android:inputtype attribute in layout xml restrict input numbers (and numeric keyboard).
Comments
Post a Comment