PenaA
PenaA

Reputation: 43

writing a translator similar to pig latin in java

So far I've been trying to write a program that's supposed to translate an English sentence to a language similar to pig Latin. Here's what the question looks like.

and this is what I'm supposed to translate:

The rain in Spain stays mainly on the plain but the ants in France stay mainly on the plants

this is supposed to become like this:

The ain-reh in-eh Spain stays ainly-meh on-eh the plain ut-beh the ants-eh in-eh France stay ainly-meh on-eh the plants

I've written the code, however, it only seems to translate one word at a time rather than the whole sentence. if i translate the whole sentence, i get an error message.

import java.util.Scanner;

public class PartD {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter a phrase to convert: ");

        String phrase = keyboard.nextLine();

        String[] words = phrase.split(" ");

        for(int i = 0; i < words.length; i++ ) {
            char firstLetter = (words[i].charAt(0));
            if (firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' || firstLetter == 'o' || firstLetter == 'u') {
                String vowel = words[i] +"-eh";
                System.out.print(vowel);
            } else {
                String start = words[i].substring(0,1);
                String end = words[i].substring(1,phrase.length());
                System.out.print(end + "-" + start + "eh" );
            }
        }
        System.out.println( );
    }
}

Upvotes: 1

Views: 325

Answers (1)

HulkSmash
HulkSmash

Reputation: 396

This line:

    String end = words[i].substring(1,phrase.length());

is using the length of the entire initial string.

You want the length of the word you parsed, eg

    String end = words[i].substring(1,words[i].length());

Also, add a space to each word you create to break up the result, eg

    String vowel = words[i] +"-eh "; // note the added space

Upvotes: 0

Related Questions