mardi 6 mars 2018

Pig latin using StringBuilder in java

I am writing an English to pig Latin translator in java using the StringBuilder methods. However, I hit a snag. What I am trying to do is make the program continue to replace the first consonants of the word that was input by the user until a vowel is found. Afterwards, it needs to print out the word starting with the vowel, and ending with the removed consonants + ay. For example: 'cricket' would be 'icketcray', and 'the' would be 'ethay'. Any help would be appreciated. I saw someone use a cutter variable on here once but I do not know how to implement it within my code as it uses StringBuilder rather than just String. Here is my Code (I went ahead and made an selection statement that checks for the second substring of the word, but I wanted to make it more dynamic and find every consonant before a vowel.): `import java.util.Scanner;

public class PigLatin
{
  public static void main(String[] args)
 {
    Scanner scn=new Scanner(System.in);
    String pigLatinWord= "";
    String word;

    System.out.print("Enter a lowercase word >>> ");
    word=scn.nextLine();
    StringBuilder pigWord = new StringBuilder(word);

    if (word.charAt(0)=='a' ||word.charAt(0)=='e' || word.charAt(0)=='i' || 
    word.charAt(0)=='o' || word.charAt(0)=='u' )
    {
        pigWord.append("ay");
    }
    else
    {

            if (word.charAt(1)!='a' && word.charAt(1)!='e' &&  
             word.charAt(1)!='i' && word.charAt(1)!='o' &&  
             word.charAt(1)!='u' && word.charAt(1) != 'y' ) //This can be 
                                                            // removed 
            {
                pigWord.replace(0, word.length(),  word.substring(2) 
                +word.charAt(0) +  word.charAt(1) + "ay");
            }
            else
            {
                pigWord.replace(0, word.length(),  word.substring(1) + 
                word.charAt(0) + "ay");
            }



    }
        pigLatinWord += pigWord + " ";
        System.out.println(pigLatinWord);
  }


}`

Aucun commentaire:

Enregistrer un commentaire