Gihadi Gihadi - 4 months ago 26
Java Question

Pig Latin Translate (Sentence)

I am making a Pig Latin translator and I don't really knwo where to go from here. I have the basic code, but I need to revise it in order for it to translate a whole sentence. If anyone can tell me how to use my String[] words I would really appreciate it. Thanks a lot!

import java.io.*;
import java.util.*;
import java.util.Arrays;

public class Main
{
public static void main (String[] args)
{
System.out.print("Please enter a phrase to translate: ");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
String[] words = str.split("\\s+");
String answer = "";
if (str.startsWith("a") || str.startsWith("e") || str.startsWith("i") || str.startsWith("o") || str.startsWith("u"))
{
System.out.print(str + "way");
}
else
{
answer = str.substring(2,str.length());
String answer2 = str.substring(1,str.length());
String answer3 = str.substring(3,str.length());
String answer4 = str.substring(4,str.length());
String d = str.substring(0,4);
if (!(d.contains("a") || d.contains("e") || d.contains("i") || d.contains("o") || d.contains("u")))
{
System.out.print(answer4 + d + "ay");
}
else
{
String c = str.substring(0,3);
if (!(c.contains("a") || c.contains("e") || c.contains("i") || c.contains("o") || c.contains("u")))
{
System.out.print(answer3 + c + "ay");
}
else
{
String b = str.substring(0,2);
if (!(b.contains("a") || b.contains("e") || b.contains("i") || b.contains("o") || b.contains("u")))
{
System.out.print(answer + b + "ay");
}
else
{
String a = str.substring(0,1);
if (!(a.contains("a") || a.contains("e") || a.contains("i") || a.contains("o") || a.contains("u")))
{
System.out.print(answer2 + a + "ay");
}
}
}
}
}
}
}

Answer

This should translate each word in that array, just use a for loop around your whole if block

for(String word: words) {
   //put your whole if block here
   //word is the variable to translate (i.e. word.startsWith("a"))
}

alternatively for beginners:

for(int i = 0; i < words.length(); i++) {
  //put if statements here
  //words[i] is the variable to translate (i.e. words[i].startsWith("a"))
}

You will also need to change all str references inside the loop to word[i], since that is the variable you want to use.