猪拉丁语翻译器在从向量中获取项目时发出越界消息


package piglatinTranslation;
import java.util.Scanner;
import java.util.Vector;
public class PigLatin {
public static void main (String[]args)
{
Scanner Input = new Scanner(System.in);
int words = 1;
Vector<Object> spacesList = new Vector<Object>();
Vector<Object> translatedWordList = new Vector<Object>();
String Phrase = Input.nextLine();
Input.close();

//Compares each character in the string 'Phrase'
//If a character is found as an empty space, it adds to the word count and saves the index of the space in a vector
for(int v = 0; v < Phrase.length(); v++)
{
char temp = Phrase.charAt(v);
String tempString = Character.toString(temp);
if(tempString.equals(" "))
{
words++;
spacesList.add(v);
}
}

//Takes each item in the vector (an integer for the index of each space within the sting)
// and creates a substring for each word, putting it though the translation method
// The translated word is added to a vector of strings
for(int v = 0; v < words; v++)
{
if(v == 0)
{
int subStrEnd = (int) spacesList.get(v);
Phrase.substring(1, subStrEnd);
translatedWordList.add(Translate.translateWord(Phrase));
}   
else
{
int subStrStart = (int) spacesList.get(v - 1); 
int subStrEnd = (int) spacesList.get(v);
Phrase.substring(subStrStart, subStrEnd);
translatedWordList.add(Translate.translateWord(Phrase));
}
}

//Takes each string in the vector and combines them into one string to be returned to the user
for(int v = 0; v < words; v++)
{
Phrase.concat((String) translatedWordList.get(v));
}
System.out.println(Phrase);
}
}

用户应该能够输入一个字符串,并通过猪拉丁语回复他们。 例如: 输入:你好 输出:埃洛海

输入:你好,你好吗 输出:ellohay, owhay areyay ouyay

我在第 43 行不断收到越界错误。

理论上,该行应该使用临时变量"v",并将其用作指针,以获取存储的整数,即空格的索引,用于将字符串分隔为单词子字符串。

您的向量填充正确,只是当有 n 个单词时,只有 n - 1 个空格。所以你只想循环到单词 - 1。一般来说,在这些类型的情况下,你只需要使用spacesList.size((,你根本不需要使用变量这个词。

相关内容

最新更新