gpt4 book ai didi

java - pig 拉丁语程序 - 元音问题

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

我正在编写一个有两个规则的程序:
1. 如果单词的第一个字符是元音,则将其移至单词的末尾。
2. 如果单词的第一个字符是辅音,则将其移动到单词的末尾并附加“ae”。

import java.util.Scanner;

public class Program5 {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String english = scanner.nextLine();
String piggy = piggyEnglish(english);
System.out.print("Translated: " + piggy);
}
private static String piggyEnglish(String s) {
String piggy = "";
int i = 0;
while (i<s.length()) {

while (i<s.length() && !isLetter(s.charAt(i))) {
piggy = piggy + s.charAt(i);
i++;
}

if (i>=s.length()) break;

int begin = i;
while (i<s.length() && isLetter(s.charAt(i))) {
i++;
}

int end = i;
piggy = piggy + piggyWord(s.substring(begin, end));
}
return piggy;
}

private static boolean beginsWithVowel(String word){
String vowels = "aeiou";
char letter = word.charAt(0);
return (vowels.indexOf(letter) != -1);
}

private static boolean isLetter(char c) {
return ( (c >='A' && c <='Z') || (c >='a' && c <='z') );
}

private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split) + word.substring(0, split);
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}

private static int firstVowel(String word) {
word = word.toLowerCase();
for (int i=0; i<word.length(); i++)
if (word.charAt(i)=='a' || word.charAt(i)=='e' ||
word.charAt(i)=='i' || word.charAt(i)=='o' ||
word.charAt(i)=='u')
return i;
return 0;
}
}

以下是预期输出:

Please enter a sentence: today is a beautiful day 
Translated: odaytae si a eautifulbae aydae

但是,这就是我得到的:

Please enter a sentence: today is a beautiful day
Translated: odaytae is a eautifulbae aydae

基本上,它不会翻译任何以元音开头的单词。我认为问题源于 PiggyWord 方法,但我不确定。我可以获得有关如何解决此问题的任何指示吗?

最佳答案

错误在于 piggyWord 函数:

private static String piggyWord(String word) {
int split = firstVowel(word);
if(beginsWithVowel(word)) {
return word.substring(split + 1) + word.substring(0, split + 1); //Since vowel is in 1st place, substring(0,0) returns empty string.
} else {
return word.substring(split) + word.substring(0, split)+"ae";
}
}

关于java - pig 拉丁语程序 - 元音问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38560174/

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