Reputation: 35
I am currently writing a Java program for AP computer science, with the goal to translate an English sentence into Pig Latin. My full program code is http://pastebin.com/PJgpveAh
But the main issue (I believe) is the
public static String pigLatSent(String sent)
{
sent.trim();
String finalSent="";
ArrayList<Integer> spaceIndexes= new ArrayList<Integer>();
spaceIndexes.add(0);
for(int i=0;i<sent.length();i++)
{
if(sent.charAt(i)==' ')
{
spaceIndexes.add(i);
}
}
for(int i=0;i<spaceIndexes.size()-1;i+=2)
{
int value=spaceIndexes.get(i);
int value1=spaceIndexes.get(i+1);
finalSent+=pigLat(sent.substring(value, value1))+" ";
}
return finalSent;
}
Upon the input "hello how are you" The program returns "Your translated sentence is ellohay are ay " when it should be "Your translated sentence is "Your translated sentence is ellohay owhay areway ouyay "
There must be something wrong with the indexing of the spaces. I am having a mental block.
Upvotes: 1
Views: 474
Reputation: 27525
There are two problems:
You are skipping every second word: i+=2
. This is fixed by doing i++
instead.
Once 1. is fixed, you are skipping the last word, because the list of indexes does not include the end of the string. This is fixed by doing spaceIndexes.add(sent.length());
after the first loop (which is symmetrical to spaceIndexes.add(0);
before the loop).
Then, there are a bunch of other minor problems:
sent.trim()
doesn't do what you expect. String is immutable in Java, so this expression returns the new trimmed string, which is just ignored. It sould be sent = sent.trim();
(or use a different variable for the result and use it afterwards).
The pigLat()
function receives the words (except the first one) including the leading space, e.g. it receives the following inputs in sequence: "hello"
, " how"
, " are"
, " you"
. This must be taken care of by the pigLat()
implementation.
Concatenating strings in a loop is a known antipattern — see Schlemiel the Painter's algorithm. Please consider using StringBuilder
instead.
Upvotes: 3