Creating a prompt within a while loop

Issue with the code is that it should only progress if the user inputs "rock", "paper" or "scissors". However, after re-entering any input the second time, it still moves on despite passing the condition in the while loop. For instance, entering "asdf" prompts for re-entry, but then if "asdf" is entered again, it exits the loop and logs out "asdf". The goal is to continue prompting the user until they enter one of the specified choices

let userChoice = prompt("Enter rock, paper, or scissors", "rock").toLowerCase();

while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
  userChoice = prompt("Please enter again");
}

console.log(userChoice);

Answer №1

If the user tries to enter multiple times, the system will reject them and exit.

     let userResponse = prompt("Type rock, paper, or scissors").toLowerCase();
        while (userResponse != "rock" && userResponse != "paper" && userResponse !=
            "scissors") {
            userResponse = prompt("Please try again");
           
        }
        console.log(userResponse)

Answer №2

Once you set userChoice to "paper", "scissors", or "rock", it will remain that way unless changed, preventing the while loop from restarting.

After running the code following the while loop, consider adding something like this:

while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors" ) {
  userChoice = prompt("Please re-enter");
}

console.log(userChoice);

userChoice = 0;

Keep in mind that this approach is effective only when your code is embedded within another loop:

loop{
    var userChoice = prompt("Enter rock, paper, or scissors", "rock").toLowerCase();

    var userChoice = prompt("Enter rock, paper, or scissors", "rock").toLowerCase();


    while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors" ) {
      userChoice = prompt("Please re-enter");
    }

    console.log(userChoice);
    userChoice = 0;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Checking the validity of email domains in real-time using Javascript

Is there a way to dynamically validate domains using JavaScript? I have a specific requirement which involves validating domains that are dynamically generated from user input. The goal is to match the domain with the company name selected and determine i ...

Ways to retrieve information from a promise that has been rejected

Can someone provide me with detailed information on why a request failed, such as an existing username or email already in use? The console only displays a generic "Bad Request" error without specifics. I noticed that I can return a promise containing data ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

AngularJS is patiently anticipating the population of the scope for ng-show

I have implemented ng-show to display an error message based on an array. The code I used is ng-show="!items.length". However, since the items are populated after a request, there is a flickering effect for a brief moment before the items are loaded. Is th ...

Instructions on merging elements in an array with identical property values

Consider the array below: [{a:1,b:1},{a:5,b:2},{a:10,b:2},{a:20,b:3}] Is there a way to create a new array that merges elements with the same b value, while adding up the corresponding a values? The desired output should be as follows: [{a:1,b:1},{a:(5+10 ...

Beginning external plugin in Angular 4 application

Is it possible to incorporate an external plugin into an Angular 4 application? I am looking to utilize the niceScroll plugin for a scrollable div, which is defined within a component. <div class="d-flex" id="scrollable"> <app-threads-list> ...

Error encountered while trying to install the node module, code 1. Installation failed

npm ERR! code 1 npm ERR! path D:\Neneng\a) Neneng_Pribadi File\2] Raynar abiyu diera\Rays DEV\Atomic BOT\node_modules\canvas npm ERR! command failed npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c ...

Utilize the push method to form a new array

var teamMembers = [ ['John D. Adams', '1959-1967', 'Ohio'], ['Dawson Mathis', '1971-1981', 'Georgia'], ]; To generate this dynamically, I am implementing the code below: var data = ne ...

Tips for assigning a default value when an error occurs

Currently diving into the world of React and experimenting with rendering 10 pieces of data from a specific API. After crafting a function to iterate through the fetched information, extracting the title and image has been quite the challenge: for (let ...

Hiding a Blogger section when its widget is not visible

Take a look at this code: <b:section id='page-list'> <b:widget id='PageList1' locked='false' type='PageList' version='2' visible='true'> </b:widget> </b:section> I wa ...

What sets these async method declarations apart?

What goes on behind the scenes? const facade = { // A: doSomething: async () => await delegatedFunction(), // B: doSomething: async () => delegatedFunction(), // C: doSomething: () => delegatedFunction(), // D: do ...

Access and retrieve numerous variables from the data object sent back through an ajax request

When using jQuery to make an ajax call to an MVC controller, the goal is to return multiple variables from the controller. What is the best way to package this data in the controller and then extract it using jQuery? ...

Creating a multi-step form in Rails without using the Wizard gem allows for more

My Rails 3.2.14 app gathers call data and the new/edit action form is quite lengthy on a single page. I am interested in implementing a multistep form using JS/client side processing to navigate between steps. While considering the Wicked Gem for multi-ste ...

Automatically Modify Uploaded Files on the Server

There is one thing that has caught my attention. I am interested in working with scripts that can automatically edit a file once it's been uploaded. For example, imagine having a form where someone uploads an HTML file. The script would then edit spe ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

What is the best way to implement smooth scrolling to an anchor tag from a different page in NextJS?

In my NextJS project, I have two main pages - the Home page and the Leaderboard page. The navigation bar code looks like this: <div className={styles.navItem}> <Link href="/"> <a className={styles.navLinks} onClic ...

Click on another part of the page to reveal a dropdown menu

I am seeking a way to trigger the opening of this dropdown select not by directly clicking on its position, but rather by clicking on another <span>. Displayed below is the dropdown menu: <div class="styled-select"> <span id="camDurati ...

Eliminating duplicate loading of jQuery in Django SmartSelect

I'm facing an issue with Django's app, smart select, as it tries to load jQuery on its own. I've already loaded jQuery in the header and then loaded JQuery UI related stuff. However, smartselect also loads jQuery again in the body, causing p ...

Evaluation of jQuery code

Just starting out with jQuery and programming in general. I posted my first hour of work here and would appreciate some feedback on how to improve it. $(function() { function hideElements() //Hides specified elements on page load. { $("li.credentia ...

Creating a process to automatically generate an input field upon the selection of checkboxes

Is there a way to automatically generate a text field for each checked box in a dynamically changing checkbox list? Below is my code snippet: <div> <label> Products </label> <li ng-repeat="item in INDproducttypes"> ...