-2
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);

    }

}

用户应该能够输入一个字符串,并通过 pig Latin 翻译回复给他们。例如:输入:Hello 输出:Ellohay

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

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

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

4

1 回答 1

0

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

于 2019-12-01T00:36:11.703 回答