gpt4 book ai didi

java - 字符串操作时出现 IndexOutOfBound 错误

转载 作者:行者123 更新时间:2023-11-30 06:25:07 25 4
gpt4 key购买 nike

这是 JAVA 中的 pig 拉丁语翻译器的代码,它只适用于一个单词,但不能用于一个句子。第 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;
}

}

最佳答案

试试这个;

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"));
}
}

关于java - 字符串操作时出现 IndexOutOfBound 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47331991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com