免責聲明:我是直接從AP計算機科學入門的初學者。獲取java.lang.StringIndexOutOfBoundsException
我試圖做一個應用程序,將用戶的文本輸入轉換爲豬拉丁文,用於練習。這是一項正在進行的工作,但到目前爲止我收到了例外。
這裏是我的代碼:
package com.example.ashavolian.piglatin2;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
TextView txtOut;
EditText txtIn;
Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOut = (TextView) findViewById(R.id.txtOut);
txtIn = (EditText) findViewById(R.id.txtIn);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String txtTxtIn = txtIn.getText().toString();
txtOut.setText(translate(txtTxtIn));
}
});
}
public String translate(String txtTxtIn)
{
txtTxtIn += " ";
int length = txtTxtIn.length();
String pigLatin = " ";
for (int b = 0; b < length; b++) {
int space = txtTxtIn.indexOf(" ");
String word = txtTxtIn.substring(0, space);
int a = word.indexOf("a");
int e = word.indexOf("e");
int i = word.indexOf("i");
int o = word.indexOf("o");
int u = word.indexOf("u");
int vowels[] = {a, e, i, o, u};
for (int c = 0; c < 4; c++)
{
if (vowels[c] == -1)
vowels[c] += 101;
}
for (int d = 0; d < 4; d++)
{
if (vowels[d] > -1 && vowels[d] <= vowels[0] && vowels[d] <= vowels[1] && vowels[d] <= vowels[2] && vowels[d] <= vowels[3] && vowels[d] <= vowels[4])
{
word = word.substring(vowels[i] + 1) + word.substring(0,vowels[i]);
pigLatin += " " + word;
}
}
txtTxtIn = txtTxtIn.substring(space + 1);
}
return pigLatin;
}
}
的異常,只有當你按下按鈕時。使程序崩潰。
這裏的例外:
FATAL EXCEPTION: main
Process: com.example.ashavolian.piglatin2, PID: 2991
java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=-1
at java.lang.String.startEndAndLength(String.java:298)
at java.lang.String.substring(String.java:1087)
at com.example.ashavolian.piglatin2.MainActivity.translate(MainActivity.java:39)
at com.example.ashavolian.piglatin2.MainActivity$1.onClick(MainActivity.java:27)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
你是否已經通過調試器完成了代碼? –
你爲什麼歧視元音'u'? – fukanchik
'元音[c] + = 101;'然後您正在嘗試'word.substring(元音[i] + 1)' – fukanchik