Я создаю код, который переводит слово (полученное пользователем) в Pig Latin.Мой код работает действительно хорошо, за исключением одной вещи.Я хочу, чтобы пользователь набрал «y» или «n», чтобы определить, будет ли выполняться код или нет.Я использую цикл while, чтобы определить, что выполнять.Если пользователь вводит что-либо, кроме двух, перечисленных выше, я хочу, чтобы он спросил снова.На данный момент у меня есть заполнитель, который называет пользователя глупым и перезапустить код.Как я могу сделать это?Большое спасибо всем!
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String playGame;
String word;
// Explains what the program does \\
System.out.println("Welcome to Coulter's Pig Latin Translator!");
System.out.println("If you choose to play, you will be asked to type a word which will be translated.");
System.out.println();
// Asks the user if they would like to play and checks 'y' or 'n' using a while statement \\
System.out.println("Would you like to play? [y/n]: ");
playGame = stdIn.next();
while(playGame.equals("y") || playGame.equals("n")) // While expression that will check if the user enters a 'y' or 'n'
{
if (playGame.equals("y")) // Executes if the user entered 'y'
{
System.out.println("Please enter the word that you would like to translate: ");
word = stdIn.next(); // Receives the word the user wishes to translate
System.out.println("_______________________________________________________");
System.out.println();
System.out.println("You entered the word: " + word); // Displays what the user entered
System.out.println();
System.out.println("Translation: " + solve(word)); // Displays the solved word
System.out.println();
System.out.println("Thanks for playing!"); //
return; // Ends the code
}
else if(playGame.contentEquals("n")) // Executes if the user entered 'n'
{
System.out.println("That's okay! Come back when you want to.");
return; // Ends the code
}
}
System.out.println("_______________________________________________________");
System.out.println("Don't be silly. Restart and type either 'y' or 'n'"); // Tells the user to restart if they entered anything but 'y' or 'n'
}
// Word translator code using a new static\\
public static String solve (String word)
{
String temp = word.toLowerCase();
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // Stores vowels in an array
char first = temp.charAt(0); // Defines first character for later use
for (int i = 0; i < vowels.length; i++) // Looks for first vowel to replace it
{
if (first == vowels[i])
{
return word + "way"; // Replaces checked vowel
}
}
word = word.substring(1); // Returns the string to the end of the word
word += first + "ay";
return word; // Returns the translated word to the program above
}
}