IndexOutOfBound错误与字符串操作

时间:2017-11-16 14:18:01

标签: java string indexoutofboundsexception

这是JAVA中猪拉丁语翻译的代码,它只用一个词,但从不用句子。第30行的代码似乎搞乱了所有内容,我不确定它是如何做到这一点或我如何解决它。第8行和第30行的IndexOutOfBoundError。我不知道如何解决这个问题,帮助。

    public class Practice 
    {
        public static void main(String[] args)
        {
            String a = "hello Stranger";

        System.out.println(translate(a)); //8
    }

    private static String translate(String a)
    {
        String XD = a;
        boolean repeat = true;
        int first = 1;
        int second = 0; 

        do
        {
            second = XD.indexOf(" ");

            if (second == -1)
            {
                repeat = false;
                XD = vowelFinder(a);
                break;
            }
            else
            {
              XD = XD + vowelFinder(a.substring(first, second)); //30
            }


            first = second +1;
        }while(repeat == true);

        return XD;
    }

    private static boolean isVowel (char c)
    {
        if (c == 'a'|| c== 'e'|| c== 'i' || c == 'o' || c== 'u')
        {
            return true;
        }

        return false;
    }

    private static String vowelFinder(String s)
    {
        String nope = s;

        for(int i = 0; i <= s.length(); i++)
        {
            if(isVowel(s.charAt(i)) == true)
            {
                nope = nope.substring(i) + "-"+nope.substring(0, i);`
                return nope;
            } 
        }  

        return nope;
    }

}

1 个答案:

答案 0 :(得分:1)

试试这个;

import java.util.Scanner;

public class PigLatin {
    public static void main(String[] args) {
        Scanner input = new Scanner( System.in );
        String yourSentence="";
        do {
            String[] words;
            System.out.print("Enter your words here: ");
            yourSentence = input.nextLine();
            words = yourSentence.split(" ");
            for (String word : words) {
                if (word.startsWith("a") || word.startsWith("e") || word.startsWith("i") || word.startsWith("o") || word.startsWith("u"))
                    System.out.print(word + "way ");
                else if (word.startsWith("sh") || word.startsWith("ch") || word.startsWith("th"))
                    System.out.print(word.substring(2)+word.substring(0,2)+"ay ");
                else
                    System.out.print(word.substring(1)+word.substring(0,1)+"ay ");
        }
        System.out.println();
        } while(!yourSentence.equals("quit"));
    }
}