0

我在获得一种在 Java 中正常工作的方法时遇到了一些问题。在程序中,我创建了一个由许多不同长度的单词组成的数组。我正在研究的方法应该采用字符串的前 3 个字母。我正在使用 obj.substring(0,3)。但我得到了 StringIndexOutOfBoundException。谁能帮我解决这个问题。这是我的代码:

            private void singleCurrencyAsynctaskCaller() {
    isSingleCurrencyResultOk = false;
    String from = subSpinner1.getSelectedItem().toString().trim();
    String to = subSpinner2.getSelectedItem().toString().trim();
    String from1 = from.substring(0, 3);
    String to1 = to.substring(0, 3);

    if (!from1.equals(to1)) {
        String RESTURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"
                + from1
                + to1
                + "%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

        AsyncTaskSingleCurrency singleCurrencyAsyncTask = new AsyncTaskSingleCurrency(
                ConverterActivity.this,
                new FetchSingleCurrencyTaskCompletedListner());
        singleCurrencyAsyncTask.execute(RESTURL);

    } else {

        currencySingleRate = 1.0;
        isSingleCurrencyResultOk = true;
        callCurrencyLogic(true);
    }
}

我得到了这个例外:

            java.lang.StringIndexOutOfBoundsException in java.lang.String.substring

            java.lang.StringIndexOutOfBoundsException
           at java.lang.String.substring(String.java:1579)
            at   com.zyksa.converter.
        ConverterActivity.singleCurrencyAsynctaskCaller(ConverterActivity.java:402)
         at com.zyksa.converter.ConverterActivity.onClick(ConverterActivity.java:580)
         at android.view.View.performClick(View.java:2408)
       at android.view.View$PerformClick.run(View.java:8816)
       at android.os.Handler.handleCallback(Handler.java:587)
        at android.os.Handler.dispatchMessage(Handler.java:92)
       at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:4627)
       at java.lang.reflect.Method.invokeNative(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:521)
4

2 回答 2

0

尝试这个:

String from1 = from.substring(0, 2);
String to1 = to.substring(0, 2);
于 2013-05-24T13:01:29.870 回答
0

可能是你的String长度不够。尝试这个 :

String yourString;
.
.
String subString;
if (yourString.length() > 3)
    subString = yourString.substring(0, 3);
else
     // Do something else

在你的情况下

String from1, to1;
if(form.length() > 3)
     from1 = from.substring(0, 3);
else
     // Do somthing else

if(to.length() > 3)
     to1 = to.substring(0, 3);
else
     // Do somthing else
于 2013-05-24T13:12:48.140 回答