Reputation: 364
i want to write a program to convert English to Piglantin using Java,but unlike the traditional way i want to store the vowels in an array...but apparently that doesn't work,i have my boards tomorrow and it would be quite helpful if you could point out my mistake....here's the program snippet
class Piglatin_2
{
public static void main(String s)
{
s = s.toUpperCase();
char c[] = {'A', 'E', 'I', 'O', 'U'};
String a = "";
for(int i = 0; i < s.length(); i++)
{
for(int j = 0; j < 5; j++)
{
if(s.charAt(i) == c[j])
{
a = s.substring(i) + s.substring(0, i) + "AY";
break;
}
}
}
System.out.println("Piglatin:"+a);
}
}
I am using the string "London" as an input. The supposed output should be "ONDONLAY" But i am getting "ONLONDAY"
Upvotes: 1
Views: 1502
Reputation: 1094
I think when you break
, you have to break out of both loops. Right now your break
statement only breaks out of the inner loop. Try this:
public static void main_other(String s)
{
s = s.toUpperCase();
char c[] = {'A', 'E', 'I', 'O', 'U'};
String a = "";
outerloop:
for(int i = 0; i < s.length(); i++)
{
for(int j = 0; j < 5; j++)
{
if(s.charAt(i) == c[j])
{
a = s.substring(i) + s.substring(0, i) + "AY";
break outerloop;
}
}
}
System.out.println("Piglatin:"+a);
}
Upvotes: 1
Reputation: 318
Firstly, your main method has to take an array of strings, like Michael's comment says. This will work in your favor as well if you are trying to translate each word. If you run your program with a sentence as arguments, the your args[] array will contain each word that is split by white space. For instance, if your sentence is "Hello World" and you run it with
$ java -jar myapplication.jar hello world
then your args array will look like
args[0] = hello
args[1] = world
from there you should be able to iterate though the array and translate each word to pig latin.
[OPINION] If you're just wanting to have a script to pass a sentence to and return pig latin, using Java is kind of line landing a 747 on the freeway. You may want to use something like python or even a shell script if you're using unix. Otherwise, you may consider having a loop that keeps the program running and taking input with a BufferedReader and that way you can keep translating sentences until you end the program.
Upvotes: 0