How do I close a prompt upon clicking cancel in JS? - javascript

I cannot for the life of me figure out how to close the prompt altogether upon pressing cancel in my code for a guessing game. I've tried several things, but each time either the code ignores what I'm trying to do, or ends in an error. Here's the code in question:
let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);
let numTries = 1
console.log(numGuess);
numGuess = parseInt(numGuess)
if (prompt == null) {
alert (`Press F5 to play again.`)
}
if (numGuess === num) {
alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);
}
else while ((numGuess !== num) && (numTries <3))
{
numTries = numTries++
alert (`Incorrect guess. Try again.`)
}

Check for the user input value, not for prompt. And also don't use while loop here .Loop is used for the traverse.
let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);
let numTries = 1
console.log(numGuess);
numGuess = parseInt(numGuess)
if (!numGuess) {
alert (`Press F5 to play again.`)
}
else if (numGuess === num) {
alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);
}
else{
numTries = numTries++
alert (`Incorrect guess. Try again.`)
}

The main issue with your code is using "++" after numTries which make the numTries variable value doesn't change and the while loop continues working without stopping, you need to insert it before.
ex:
++numTries
The code below is a working example of what you want to do.
let numGuess;
let numTries = 0;
let num = 4;
const guessFunction = () => {
if (numTries >= 3) {
alert("Sorry you Failed in the 3 tries! Press F5 to play again.");
return;
}
numGuess = parseInt(
prompt(`Guess the number I am thinking of (between 1 and 10):`)
);
numTries = ++numTries
if (numGuess === num) {
alert(`Correct! You guessed the number in ${numTries} try! Press F5 to play again.`);
return;
}
if(numTries <= 2) {
alert(`Incorrect guess. Try again.`);
}
guessFunction()
};
guessFunction()

Related

A banking function that loops user input and increments/decrements until exit key is entered in js

I am trying to write a function that gives a user 4 choices, does what they choose and then asks them the first 4 choices again and again until they exit.
I have tried using an if/else loop inside a while loop, but that just takes the first user input and loops at that point. It also concatenates the balance when I try to add the two numbers. I assume that due to the fact that the prompt is a string and assigns a string to the variable. I am using console.log() to try and see what is happening while everything is running, but to no avail.
Sorry if this is a lengthy post and redundant.
let balance = 0;
let deposit = 0;
let withdraw = 0;
function bankFunction (banked) {
alert('Hello, how can I help you today?');
let input = prompt('Q to quit the application \nW to withdraw \nD to deposit \nB to view balance');
while (input != 'Q') {
if (input === 'W') {
withdraw = prompt("Withdraw how much?");
console.log(withdraw);
balance = balance - withdraw;
console.log(balance);
} else if (input === 'D') {
deposit = prompt("Deposit how much?");
console.log(deposit);
balance = balance + withdraw;
console.log(balance);
} else {
alert("done");
break;
}
}
}
If you want to continuously prompt the user for inputs, then the prompt function should be inside your loop too. The essential pseudo code is: "While the input is not "Q", continue to prompt for a user choice".
Implementation:
let input = "A" // Initial input to get the loop working
while (input !== "Q") {
// Get actual user input
input = prompt("Choose Q or W or D or B");
if (input === "W") {
// Withdraw logic
}
else if (input === "D") {
// Deposit logic
} else if (input === "B") {
// ...
}
}
Note that there is a bit of a little gimmick here: I needed to have an initial input ("A") to get the first round of the loop working - since in the first round of the loop, user input has not been received yet. Once it get past that initial first round, the input variable is being continuously re-assigned through the user prompt, and the loop will exactly how the pseudo-code described it.
If you don't like that gimmick, there is another way, called the While-True-Break loop. The essential idea is that: The loop will automatically run forever, until you explicitly stop it (via break statement)
let input;
while (true) {
input = prompt("Choose Q or W or B or D");
if (input === "Q") {
// Stop the program loop
break;
} else if (input === "W") {
// ...
} else if ...
}

Loops and counting

I want to make it so when someone answers the prompt they can answer a number 1 through 6 and to exit to just enter 0. After that I want them to be able to enter a number and that number will be correlated to an image or a link. Example: I have 3 different kinds of candy and I want 1 to be skittles, 2 to be m&ms, and 3 to be jolly ranchers. When the user enters 1 they will have an image come up that is skittles, and when they enter 2 an image of m&ms will come up. This is the code I have so far. If anyone could help me I would greatly appreciate it!
var stop = '0'
while(true) {
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === stop){
break;
}
}
You can have an array of image urls and select any of them by the number the user has entered.
var images = ['xxx.jpg','yyy.jpg', 'zzz.jpg']
var stop = '0'
while(true) {
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === stop){
break;
}
else{
if (!IsNaN(input) && images.length >= input)
showImage(images[input - 1]); //a mock function
}
}
I would approach your problem like this. Just catch the input and process it inside your while loop.
var pictures = [...] // array of pictures
while(true){
var input = prompt('Give a number 1 through 6. Type 0 to exit.');
if(input === '0'){
break;
}else{
if(pictures.length >= input) {
showMyImage(pictures[input - 1])
// or do anything else with your image (e.g. error handling etc.)
}
}
}
Hope this can help!

alert does not process user input

I'm working on conditional statements in js. But ran into 2 problems with this script.
1) regardless of user input, the script doesn't process the else clause.
2) my alert method prints first the if alert(), then secondly an undefined alert(). Idk why this is.
<script>
function temperature (temp)
{
var message="";
var temp = 70;
if(temp <= 69) {
alert(message = "Turn on the heat.");
} else {
alert(message = "It is hot enough.");
}
}
</script>
Then my body script is:
<script>
var myTemp=prompt("Please enter your current temperature."); //prompt is ok
//alert fails to process else clause and then prints an undefined alert()
alert(temperature(myTemp));
</script>
I have tried removing the alerts from the function itself. That, however, kills my prompt.
PS I use Sublime 3 with jshint but this problem is out of jshint's jurisdiction, obv.
Please advise and thanks all.
you are using 2 alerts: one inside the another.. and also resetting your temperature value.
Use this:
function temperature (temp)
{
if(temp <= 69) {
return "Turn on the heat.";
} else {
return "It is hot enough.";
}
}
A couple of things:
1) You are setting the variable temp to 70, so it overrides your input.
2) The prompt() function returns a string, which you are then passing into your temperature function where you are trying to compare it to integers. Use parseInt().
3) You are also nesting alerts since you put temperature() in an alert and your temperature() function itself also creates alerts. Choose one or the other.
This is how I'd change it.
<script>
function temperature (temp){
var message="";
var temp = temp || 70;
if(temp <= 69) {
message = "Turn on the heat.");
} else {
message = "It is hot enough.");
}
return message;
}
</script>
and then:
...
alert(temperature(parseInt(myTemp)));
...

Using JS to check if integer is even or pressing q to quit

The objective here is for the user to enter a number to determine whether it is even or to enter 'q' to quit the program.
var readlineSync = require('readline-sync');
var i = 0;
while (i <= 3) {
var num = readlineSync.question("Enter q to quit, or enter an integer to continue?");
if (num === 'q') {
console.log("You have quit the application. Thanks for using.");
break;
}
else if (num % 2) {
console.log("You have entered an odd number");
}
else if (num !== 'q') {
console.log("You have not entered a valid character. Please try again.");
break;
}
else {
console.log("You have entered an even number.");
break;
}
}
Pressing q initiates the appropriate response and exits the program. Entering an odd number also generates the appropriate response. However if an even number is entered, the program does not generate the appropriate response and instead reads You have not entered a valid character. Please try again. What am I overlooking? Any advice is appreciated.
It's because of your third condition (num !== 'q'). It evaluates as true when you enter an even number.

Count the number of times an input has been made javascript

What is the best practice when counting the number of times an action has been carried out in javascript? for example I have a prompt that asks for a number
var playerGuess = prompt("What is your guess ");
What i would like to do is after 3 attempts end the game with another prompt.
What I am having difficulty with is actually counting the number of inputs
Thanks
I have tried creating a function do count the number of times an input has been made
var guessCount = playerGuess.count;
function limit(playerGuess){
if (guessCount >= 3){
alert("game over");
} else{
alert("carry on");
}
}
totally wrong i know but having a go
Like so:
// Global var to hold number of guesses
var guessCount = 0;
// Function to get the guess
function getGuess() {
// Get a new guess
var guess = prompt('What is your guess ');
// Process guess here, eg:
if (...whatever tests you want to make...) {
// Good guess
alert('Good guess: ' + guess);
} else {
// Bad guess
guessCount += 1;
// Fail out if too many guesses have been tried
if (guessCount >= 3) {
alert('Game over');
return;
}
}
};
Cheers!
You should evaluate the answer you get each time.
If the answer is valid, take the count in another variable and when the count reaches the desired amount take no inputs.
var attempts = 0;
function ask_question(){
if(attempts > 3)
{
// you have played enough!
return;
}
else
{
var playerGuess = prompt("What is your guess ");
if(parseInt(playerGuess) != NaN && playerGuess != '')
{
attempts++;
// do whatever you would like to do with playerGuess
}
}
}
You could do this with a while loop and a variable to store the current iteration. Consider the following, which gives you three chances to guess the "secret" number:
var secretNumber = 42,
youWon = false,
i = 0;
while (i < 3) {
var playerGuess = prompt("What is your guess?");
if (playerGuess == secretNumber){
youWon = true;
break;
}
i++;
}
if (youWon) {
alert("You got it!");
} else {
alert("Sorry, you have no more tries left.");
}
This code loops over and over, incrementing i each time. It asks the question, and checks the answer. If the answer is right, it sets the youWon flag and breaks out of the loop, ending it early. Otherwise, the loop ends naturally after 3 iterations. After the loop is done, the youWon flag is checked to determine if the loop ended because the right answer was given, or if it ended because the number of tries was exhausted.

Categories