mercredi 12 mai 2021

While loop preventing if-else-if statements from executing when user types what should execute them [duplicate]

I'm trying to make a simple Tavern class for a game as a newcomer to Java.

The code is supposed to do three different things via a if-else-if statement based on the player's choices.

Expected results: The if statements within the while loop running after user has inputted their corresponding words after being prompted, for example, typing Items after the prompt.

Actual results:

  1. Two 'else without if' errors (most likely caused by the 'breaks' in the if statements), and removal of said breaks causes the Tavern Master to repeat his while loop spiel despite the conditions of the if-then statements being met via doing as prompted.

  2. Tried rewriting the while loop as a do-while loop which resulting in a endless stream of "The Tavern Master stares before repeating his spiel." then a repeat of said spiel.

  3. tried using .equals() to fix the while loop. Inputted Items when prompted, the if-else-if statement failed to execute.

  4. Tried replacing the .equals() with contentEquals(). Results are that ONLY the first if statement "You typed Items." executes. Typing Rumors fails to make the if else statement execute; then the "you leave the tavern" statement appears.

The following code is a MRE of my Tavern code, hilariously called MiniTavern.


 import java.util.Scanner; // needed for the scanner class

public class MiniTavern
{
    public static void main(String[] args)
    {

        /**
        * holds a number to see how many times the while loop runs.
        */

        int I = 1;

        /**
        *Prompts player's input to start if-else-if statements.
        */

        System.out.println("The Tavern Master speaks to you.");
        System.out.println(" Type the word 'Items' or 'Rumors' next. Without the '.");

    /**
    * Creates a means for the user to input stuff from keyboard.
    */

    Scanner keyboard = new Scanner(System.in);

    /**
    * stores user input from keyboard as a String.
    */
    
    String UserKeyboard = keyboard.nextLine();

    /**
    * Creates a means for the NPC to repeat instructions to user
    * should user input something thats not 'Items' or 'Rumors'.
    */

        while (UserKeyboard.contentEquals("Leave"))
    {
        System.out.println("Tavern Master repeats instructions to type Items or Rumors.");

        if (UserKeyboard.contentEquals("Items"))
        
        System.out.println("You typed Items.");
        //break;

        else if (UserKeyboard.contentEquals("Rumors"))
        
        System.out.println ("You typed Rumors.");
        //break;

        else 
        
        System.out.println("The Tavern Master stares before repeating his speil.");
        System.out.println(I);
    } 

Aucun commentaire:

Enregistrer un commentaire