Alex H. answered 08/30/16
Tutor
5
(2)
Intro to Programming Tutor (Various Languages)
Hi Laura, there are two parts to my answer:
1) Use a do/while loop and break on the String "word" being null.
do {
System.out.print("Please Enter English Word: ");
word = tread.next();
word = word.toLowerCase();
System.out.println(word);
first = word.charAt(0);
if (first == 'a' || first == 'e' || first == 'i' ||
first == 'o' || first == 'u') // vowel
pig = word + "hay";
else
pig = word.substring(1) + word.charAt(0) + "ay";
System.out.println("PIG-LATIN : " + pig);
} while ( word != null );
word = tread.next();
word = word.toLowerCase();
System.out.println(word);
first = word.charAt(0);
if (first == 'a' || first == 'e' || first == 'i' ||
first == 'o' || first == 'u') // vowel
pig = word + "hay";
else
pig = word.substring(1) + word.charAt(0) + "ay";
System.out.println("PIG-LATIN : " + pig);
} while ( word != null );
2) The issue with just the above fix is that you're still left with an issue if the user doesn't type any characters and just hits enter. The line "tread.next()" will fail. Also if the user types in an EOF character (on Mac it would be Ctrl+D). In addition, if the user were to type multiple words, it would not behave as intended. Adding the following will fix this:
public static void main(String[] args)
{
Scanner tread = new Scanner(System.in); //
String word = "", pig;
char first;
boolean next_line_exists;
do
{
System.out.print("Please Enter English Word: ");
// Read line; make sure it is not empty
next_line_exists = tread.hasNextLine();
if ( next_line_exists )
{
String line = tread.nextLine();
if ( !line.isEmpty() )
{
// Split the String and grab first word
String[] word_array = line.split(" ");
word = word_array[0];
word = word.toLowerCase();
System.out.println(word);
first = word.charAt(0);
if (first == 'a' || first == 'e' || first == 'i' ||
first == 'o' || first == 'u') // vowel
pig = word + "hay";
else
pig = word.substring(1) + word.charAt(0) + "ay";
System.out.println("PIG-LATIN : " + pig);
}
}
} while ( next_line_exists );
}
{
Scanner tread = new Scanner(System.in); //
String word = "", pig;
char first;
boolean next_line_exists;
do
{
System.out.print("Please Enter English Word: ");
// Read line; make sure it is not empty
next_line_exists = tread.hasNextLine();
if ( next_line_exists )
{
String line = tread.nextLine();
if ( !line.isEmpty() )
{
// Split the String and grab first word
String[] word_array = line.split(" ");
word = word_array[0];
word = word.toLowerCase();
System.out.println(word);
first = word.charAt(0);
if (first == 'a' || first == 'e' || first == 'i' ||
first == 'o' || first == 'u') // vowel
pig = word + "hay";
else
pig = word.substring(1) + word.charAt(0) + "ay";
System.out.println("PIG-LATIN : " + pig);
}
}
} while ( next_line_exists );
}
Hope this helps!
Alex