gpt4 book ai didi

java - Pig Latin 翻译器——寻找辅音簇。

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

我正在制作一个 Pig Latin 翻译器,将用户的输入翻译成 Pig Latin。我已经弄清楚了单词何时以元音开头以及何时不将第一个字母放在中间。然而,当涉及到辅音簇(单词中第一个元音之前的字符组)时,我只是不知道如何将它们集中到自己的变量中。我使用 for 循环来扫描字母中的第一个变量,然后尝试将所有这些字符串聚集到它自己的变量中,然后放入单词的中间。

这是我到目前为止的代码:

import java.util.Scanner;
public class Mission4
{

public static void main(String[] args)
{
Scanner in = new Scanner (System.in);

System.out.println("Please enter word to convert to Piglatin:");
String userInput = in.nextLine();

int firstV = 0;

char firstCh = Character.toLowerCase(userInput.charAt(0));

do
{

if (firstCh == 'a' || firstCh == 'e' || firstCh == 'i' || firstCh == 'o' || firstCh == 'u') //if userInput starts with vowel
{
String pigTalk = userInput + "ay";
System.out.println(pigTalk); // adding 'ay' to the end of their input
System.out.println("Enter another word to convert to piglatin, otherise press \"Q\" to exit.");
userInput = in.nextLine();
}

else //if userInput doesn't begin with vowel
{
for (int i = 0; i < firstV; i++)
{
char ch = userInput.charAt(i);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
{
firstV = Character.subString(ch);
}
}
String firstCluster = userInput.substring(0,firstV.length);
String secondCluster = userInput.substring(firstV.length,userInput.length());
System.out.println(secondCluster + firstCluster + "ay"); //Printing out their piglatin
System.out.println("Enter another word, or type \"Q\" to exit program.");
userInput = in.nextLine();
}
} while (!userInput.equals("Q")); //Giving user an exit option
}
}

你能提供什么建议吗?任何帮助表示赞赏。

最佳答案

首先,尝试将代码组织成更小的函数,形成逻辑单元。这使您和其他人更容易理解程序正在做什么以及它做错了什么。

程序中的几个错误:

  • firstV设置为 0,因此该循环立即停止:for (int i = 0; i < firstV; i++)
  • 循环已损坏(甚至无法编译)

循环需要做的是从第二个字符开始迭代,直到找到元音。

这是提取到函数中的更正后的主要逻辑,也是一个辅助函数:

public String toPigLatin(String word) {
if (isVowel(word.charAt(0))) {
return word + "ay"; // actually, wikipedia says you should append "yay", not "ay"
}
for (int i = 1; i < word.length(); i++) {
if (isVowel(word.charAt(i))) {
return word.substring(i) + word.substring(0, i) + "ay";
}
}
return word + "ay";
}

public boolean isVowel(char c) {
c = Character.toLowerCase(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}

关于java - Pig Latin 翻译器——寻找辅音簇。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37502100/

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