简体   繁体   English

android中的numberformatexception和edittext

[英]numberformatexception and edittext in android

Following code gives me numberformatexception. 以下代码给了我numberformatexception。 can you please tell me where to put exepcions or what to do about following lines? 能否请您告诉我将exepcions放在哪里或如何处理以下几行? logcat tells that there is a problem on commented line logcat告诉注释行有问题

public void zaplatiti(){
   EditText zbrojka = (EditText) findViewById(R.id.editText7);
   Float[] strings = new Float[allTexts.size()];
   Float zbroj=(float) 0;
   for(int i=0; i < allTexts.size(); i++){
       strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem


   }
   for (int k=0;k<strings.length;k++){
       zbroj =zbroj+ strings[k];}

   }
   zbrojka.setText(String.valueOf(zbroj)+"KN");

} }

for(int i=0; i < allTexts.size(); i++){
    try {
        strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem
    }
    catch (NumberFormatException e) {
        // Code to execute if the entered value is not a number
    }
}

This is also possible to avoid by only allowing your EditTexts to have numerical values. 也可以通过仅允许您的EditText具有数字值来避免这种情况。 That will force the user to only enter a numerical value in the first place, then you don't have to catch the exception. 这将迫使用户首先只输入一个数字值,然后您不必捕获异常。 But then you should check if the entered text is empty first. 但是然后您应该首先检查输入的文本是否为空。

EDIT: 编辑:

For doing this you must make an if statement, but the correct comparison beetween String values is: 为此,您必须创建一个if语句,但是字符串值之间的正确比较是:

if ( mEditText.getText().toString().equals("String to compare with")){ ... } 

the "numerical mode" of an editText could be set up in the XML file as: 可以在XML文件中将editText的“数字模式”设置为:

android:inputType = "number"

Other valid numerical modes are numberSigned and numberDecimal . 其它有效的数值模式是numberSignednumberDecimal

So after changing the input type your code could look like: 因此,更改输入类型后,您的代码应如下所示:

for(int i=0; i < allTexts.size(); i++){
    if (!allTexts.get(i).getText().toString().equals("")) {
        strings[i] = Float.valueOf(allTexts.get(i).getText().toString());////problem
    }
    else {
        // Code to execute if there is no entered value
    }
}

您是否检查过allTexts数组类型?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM