What is the best way to continue looping until my variable matches the user's input? JavaScript

As of now, this nested for loop continues until both i and j reach 3. How can I reset the variables once they have reached their maximum value so that the loop can continue running?

Alternatively, is my current approach incorrect?

for (i=1; i<=3; i=i+1)
  {
   for (j=1; j<=3; j=j+1)
     {
      ans=i + j;
      document.write(i + "+" + j + "=" + "<br />");
      var user_input = prompt("What is your answer?",0);
      while (user_input != ans) {
      if (ans == user_input)
        {
         document.write("Yes, the answer is " + ans + "<br />");
        }
      else
        {
         document.write("No, the answer is " + ans + "<br />");
        } 
      }
    }  
  }

I attempted to use a while loop, but it keeps crashing. I am struggling with the logic behind the problem.

My goal is:

If the user answers correctly at any point, the loop should end. However, I want to ensure that the sum does not exceed 6. Once it reaches 6, I would like both i and j to reset.

Answer №1

It appears that the while loop may not be necessary in this scenario. If a user answers incorrectly, they receive a new question, and if they answer correctly, the process ends. Please consider executing the following code:

var finish = false;
for (i=1; i<=3; i=i+1)
  {
   for (j=1; j<=3; j=j+1)
     {
      var ans=i + j;
      console.log(i + "+" + j + "=" + "<br />");
      var user_input = prompt("What is your answer?", 0);
      if (ans == user_input)
        {
            finish = true;
            console.log("Yes, the answer is " + ans + "<br />");
          break;
        }
      else
        {
            console.log("No, the answer is " + ans + "<br />");
        }
    }  
    if(finish){break;}
    if(i==3 && j==4){i = 0; j = 0;}
  }

Answer №2

Instead of using nested loops, I would opt for a recursive function in this scenario. Nested loops can be daunting to work with, difficult to comprehend, and more prone to causing infinite loop conditions:

var correctAnswer = 6;
function getUserInput() {
    var userInput = prompt("What is your answer?", 0);
    if (correctAnswer == userInput) {
        document.write("Yes, the answer is " + correctAnswer + "<br />");
    } else {
        getUserInput();
    } 
}

getUserInput();

If you prefer the correctAnswer value to change each time the loop runs, you could incorporate random number generation logic to determine the answer:

var correctAnswer = Math.floor(Math.random() * 6) + 1; 

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

Switching between numerical and alphabetical input using JQuery

How can I switch between allowing character and numeric input in a textbox? I currently have a JQuery function that restricts input to numbers only $('.numeric').on('input', function (event) { this.value = this.value.replace(/[^0 ...

Using Jquery to increase input values in multiples on keyup event

Is there a way to ensure that an input element only accepts numbers in increments of 50? While we know we can use the step="50" attribute, is it possible to achieve this using the keyup event instead? I came across this code that restricts users from inp ...

What is the reason behind the improved performance I experience in Chrome with the Developer Console open?

Currently, I am developing a small canvas game completely from scratch using pure JavaScript. This game utilizes a 2D lighting algorithm that is akin to the one found here. It features only one light source and 25 polygons, resulting in approximately 30,0 ...

The failover process for PayPal involves seamless transitions to backup systems in the

I am currently assisting a client with a unique architecture setup: Back End Running on Java Server Front End Powered by Proxy (Node JS + Express application) For security reasons, all requests made to the server must pass through the Proxy. We ar ...

Guide to generating interactive material-ui components within a react application?

I am facing a challenge in creating a dynamic mui grid element triggered by a button click in a React component. When attempting to create let newGrid = document.createElement('Grid'), it does not behave the same way as a regular div creation. D ...

The functionality of Skrollr on mobile is currently not working properly due to the inability to prevent default actions

Encountering the following error on all chromium browsers while using the Skrollr library and accessing the website through mobile: "[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See < ...

From javascript to utilizing ajax calls to interact with php scripts,

I am currently working on a page called edit.php where I need to pass a JavaScript variable to a modal window containing PHP in order to execute a query and retrieve data. Unfortunately, my experience with Ajax is limited and I haven't been able to fi ...

JavaScript code must be tailored to reference a JS file based on the specific environment, whether it be Production, Development, or staging

I need to determine which .js file to refer based on the URL of Prod, Dev, and QA environments. For Production URLs (domain.com and www.domain.com), I should refer to prod.js file. For Dev and QA URLs (dev.domain.com and staging.com), I should refer to s ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

Execute the script when the document is fully loaded

Is there a way to show a dialog in jQuery when the document loads without using <body onload="showdialog();">? Can the javascript code be placed in the main div or footer div to work like the onload event? <body onload="$('#dialog').sli ...

The Datatable plugin is unable to effectively customize tables that are loaded dynamically

Within my single page application, the home page initially loads all static resources and js files. Subsequently, upon a user click event, the table is dynamically loaded. Unfortunately, the datatable customization does not seem to be applied on the newly ...

A guide to showcasing JSON data on a webpage using JavaScript

I am currently working on a SOAP WSDL invocation application in MobileFirst. The response I receive from the SOAP WSDL is in JSON format and is stored in the result variable. When trying to access the length of the response using result.length, I encounter ...

In IE8, submitting an Ajax request almost always results in an error being

This piece of code seems to be causing some trouble, as it works fine in all browsers except for IE8 on an XP machine. No matter what I try, the error function keeps getting triggered specifically in IE8. I've experimented with different dataTypes lik ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

Ability to access functions from required modules that are defined within the calling module

Is there a way to call a function within a required module that is defined in the main program without copying or creating separate files? Main.js: var http = require('http'); var aFunc = function() {return 1;} var bFunc = require('./bFunc ...

Issues arise with tabbed content as default content fails to display and classes are not added upon clicking

I'm currently working on a tabbed module that consists of three tabs. Here's how it operates: When the user clicks on a carousel_element, it reveals carousel_hidden-text within that div and displays it in another div called carousel_quote. I&ap ...

What are some strategies for optimizing React performance when managing controlled input from numerous components?

Building a Parent component with multiple child components, each passing data to the parent for an API call. The structure is as follows: const MainComponent = () => { const [child1input, setChild1Input] = useState(""); const [child2input, setChild ...

Executing Ajax requests with callbacks in JavaScript/jQuery

I'm facing an issue where my functions are executing before Ajax requests (first fetching local JSON, then retrieving data from an online resource) have completed. For example, I want countTheMovies to run only after all the necessary information is ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

What is the best way to define the relative path and folder paths in HTML and CSS when working in Visual Studio 2012?

Working on a basic HTML project that includes css and javascript. Within the project folders named css, scripts, and images are used for organization. The project structure can be seen in the provided image. The issue that arises is how to correctly set p ...