ATEATEEFFEEE
ATEATEEFFEEE

Reputation: 95

Trouble getting a while loop to work in JavaScript

It's a rock paper scissors game. The code in question is supposed to check user input and keep circling back while the input doesn't contain "rock", "paper", "scissors", OR if the length of input exceeds 8 characters.

Am I entering the operators correctly? I couldn't find any examples that look remotely like my code which makes me think that there's something I'm missing entirely.

I've tried moving the not operator around and it either ignores it or breaks and doesn't run.

function playerSelection () {
      let playerInput = prompt("Type Rock, Paper, or Scissors: ")

      let trimmedInput = playerInput.trim();
      
      let lowerCaseInput = trimmedInput.toLowerCase();

      let capitalizedInput = lowerCaseInput.charAt(0).toUpperCase() + lowerCaseInput.slice(1);
      
      // check user input
      while (!((capitalizedInput.includes("Rock") || capitalizedInput.includes("Paper") || capitalizedInput.includes("Scissors")) || (capitalizedInput.length <= 8))) {
        playerInput = prompt("You may only enter 8 characters. Please choose Rock, Paper, or Scissors: ");
        
        trimmedInput = playerInput.trim();
        capitalizedInput = trimmedInput.charAt(0).toUpperCase() + trimmedInput.slice(1);

      }

      return capitalizedInput;

      }

Upvotes: 0

Views: 36

Answers (1)

boppy
boppy

Reputation: 1908

This seems like a perfect scenario to use a do while, because you need an input anyways. Also, all the converting could be done at once.

There is also no need to check for the length of the input, since you have a list with the absolute truth of what can be put in. Next note: You have not implemented an "exit"-route if someone cancels the dialog. So you really end up having to input one of your truth-list entries.

My approach would be

function playerSelection(playerInput){
    do {
        playerInput = prompt("Type Rock, Paper, or Scissors: ");
        if(playerInput) playerInput = playerInput.trim().toLowerCase(); // Adding this to avoid errors if someone cancels the dialog
    } while(!['rock', 'paper', 'scissors'].includes(playerInput));
    return playerInput.charAt(0).toUpperCase() + playerInput.slice(1);
}

If you really would like to use a while-loop, it could be:

function playerSelection(playerInput){
    playerInput = prompt("Type Rock, Paper, or Scissors: ");
    if(playerInput) playerInput = playerInput.trim().toLowerCase();

    while(!['rock', 'paper', 'scissors'].includes(playerInput)){
        playerInput = prompt("You may only enter 8 characters. Please choose Rock, Paper, or Scissors: ");
        if(playerInput) playerInput = playerInput.trim().toLowerCase();
    }
    return playerInput.charAt(0).toUpperCase() + playerInput.slice(1);
}

Upvotes: 1

Related Questions