1

我有两个问题:

  1. x.substring(i,1)中断try/catch
  2. 由于这个以及可能的其他原因,我无法让这种方法起作用。我试图拥有它,所以当用户输入小数时,它会增加 的max lengthEditText但如果用户输入的数字太大,则会减少max length回原来的值。max length

    boolean tooBig = false;
    EditText txt = (EditText)findViewById(R.id.num1);
    TextView display = (TextView)findViewById(R.id.display);
    String x = txt.getText().toString(); // the String in the EditText
    String str = "didn't work";
    try
    {
        if (x.contains(".")) 
        {
            // set the max length to be 15
            if (x.length() >= 10)
            {
                // see if the decimal is contained after 10 digits
                for (int i = 10; i < x.length(); i++)
                {
                    str = x.subtring(i,1); // breaks here (test)
                    if (x.substring(i,1).equals(".")) // also breaks here
                    {
                        tooBig = true;
                    }
                }
            }
    
            if (tooBig)
            {
                // set text to be blank and max length to be 8
            }
        }
    }
    catch (Exception e) 
    {
        txt.setText(str); // "didn't work"
    }
    

我能做些什么来解决这个x.substring(i,1)问题?

4

4 回答 4

2
if (x.substring(i,1).equals(".")) // also breaks here
{
    tooBig = true;
}

必须是:

if (x.substring(i,i+1).equals("."))
{
    tooBig = true;
}
于 2013-08-10T21:43:18.360 回答
2

问题出在

   for (int i = 10; i < x.length(); i++)
    {
        str = x.subtring(i,1); // breaks here (test)
        if (x.substring(i,1).equals(".")) // startIndex say 10 is 
          greater than 1 which is wrong.
        {

您的 startIndex 总是大于 endIndex,这显然是错误的,会导致 java.lang.StringIndexOutOfBoundsException

于 2013-08-10T20:27:48.953 回答
1

这将是我新更改的代码:

boolean tooBig = false;
EditText txt = (EditText)findViewById(R.id.num1);
String x = txt.getText().toString(); // the String in the EditText
try
{
    if (x.contains(".")) 
    {
        // set the max length to be 15
        if (x.length() >= 10)
        {
            // see if the decimal is contained after 10 digits
            for (int i = 10; i < x.length(); i++)
            {
                if (x.substring(i,i+1).equals("."))
                {
                    tooBig = true;
                }
            }
        }

        if (tooBig)
        {
            // set text to be blank and max length to be 9
        }
    }
    else // no decimal
    {
        // set the max length to be 9
    }
}
catch (Exception e) {}
于 2013-08-11T23:19:41.227 回答
0

您将不得不更改(i,1)为,(i, i+1)因为在 Java 中,第二个数字是您的index end point,而不是像在其他一些语言中那样“要输入多少个字符”。您将从 开始i,并在 1 多于 1 结束i

您可以轻松地使用它indexOf(".")来解决您的问题。此外,else请声明将max length后面的内容更改为原始max length内容,以防用户删除小数点。

将您更改try为:

if (x.contains(".")) 
{
    // set the max length to be 15

    if (x.indexOf(".") > 9)
    {
        txt.setText(x.substring(0,9));   
        // set length to be 9
    }
}
else
{
    // set max length back to original
}
于 2013-08-10T20:30:51.580 回答