Вопрос относительно цикла while и как повторно задать вопрос ay / n - PullRequest
0 голосов
/ 28 февраля 2019

Я создаю код, который переводит слово (полученное пользователем) в 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
}

}

Ответы [ 3 ]

0 голосов
/ 28 февраля 2019

Вы захотите, чтобы ваша строка playGame = stdIn.next(); и приглашение запускались в начале цикла while, а не перед ним.Затем вы можете проверить, является ли это y, n или что-то еще сразу после этого.

0 голосов
/ 28 февраля 2019

Поскольку та часть вашего кода, которую вы хотите повторить, является только начальным вопросом, это все, что должно быть в цикле:

boolean askAgain = true;
while(askAgain) {
    // print your prompt;
    playGame = stdIn.next();
    if (playGame.equals("y") || playGame.equals("n")) {
        askAgain = false;
    }
}

// Now do your if/elseif for which letter was retrieved.

Хорошей практикой является циклическое выполнение только тех частей вашего цикла.код, который может фактически повторяться.

0 голосов
/ 28 февраля 2019

Ну, вы просите ввести здесь:

playGame = stdIn.next();

Это просто должно войти в ваш цикл:

playOn = true;
while(playOn) {
  playGame = stdIn.next();
  if ( y ) { ... play 
  } else {
    if ( n ) { ... dont play, set playOn = false
    } else {
      ... ask again
    } 
  }

Вышесказанное подразумевается как вдохновение, ик сведению: здесь действительно важно то, что вы получаете цепочку if / else и соответствующие «блоки».Вам нужен еще один if / else полностью в первом блоке "else"!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...