I have created a method to translate multiple lines into Pig Latin. The expected input looks like so:
The cat jumped over the fox
My code outputs the text, correctly translated into Pig Latin and with the proper formatting (i.e. words separated out, lines separated out. However, I do this by using two instances of the scanner class.
Could anyone suggest how I could remove the two instances and condense them into one?
By the way, feel free to offer any other suggestions, but bear in mind I am a novice who is still learning!
File file = new File("projectdata.txt");
try
{
Scanner scan1 = new Scanner(file);
while (scan1.hasNextLine())
{
Scanner scan2 = new Scanner(scan1.nextLine());
while (scan2.hasNext())
{
String s = scan2.next();
boolean moreThanOneSyllable = Syllable.hasMultipleSyllables(s);
char firstLetter = s.charAt(0);
String output = "";
if (!moreThanOneSyllable && "aeiou".indexOf(firstLetter) >= 0)
output = s + "hay" + " ";
else if (moreThanOneSyllable && "aeiou".indexOf(firstLetter) >= 0)
output = s + "way" + " ";
else
{
String restOfWord = s.substring(1);
output = restOfWord + firstLetter + "ay" + " ";
}
System.out.print(output);
}
System.out.println("");
scan2.close();
}
scan1.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Note: I had posted something similar on Code Overflow a few days ago and have taken some advice from the answer I was given there. However, whilst someone recommended not using two scanner classes, I just couldn’t get the formatting right.
With your outer-loop you can read the file line-by-line. With the outer-loop you treat each line read as a string.
With that you are trying to read a
Stringusing aScanner. You should change it as follows:Split the line into an array of strings (words) and work on it.
The inner loop can just iterate through the array.
Update
You can just escape the empty lines as follows. Any exception handling is not required.