How do I "restart" if statement if a condition is met? - javascript

I'm very new to javascript. I wanted to make a quick program that generates the youngest age possible a person is able to date given their age, using the formula my dad taught me. In my code I have a condition where if my var (dateage) isn't a number, the user is asked to please enter in a number. I want the program to then re-ask the variable assignment prompt until a number is given.
var dateage = prompt("How old are you?");
if(dateage >= 14){
dateage = dateage/2 + 7;
alert("The youngest you can date is " + dateage)
} else if(isNaN(dateage)){
alert("Please enter in a number");
} else
alert("You're too young to date.");
You can see that if dateage isn't a number, the user is alerted. At that point I want the prompt to appear again asking the user for their age. How can I do this?

Put it in a function so you can re-invoke
function checkAge() {
var dateage = prompt("How old are you?");
if(dateage >= 14){
dateage = dateage/2 + 7;
alert("The youngest you can date is " + dateage)
} else if(isNaN(dateage)){
if (confirm("Please enter in a number")) checkAge();
} else
alert("You're too young to date.");
}
checkAge();
I used a confirm for the re-check because this means you can more easily escape from an infinite loop situation. If you don't want to pollute the namespace, you can write this as a named IIFE, and if you don't want to carry the stack over, you can invoke through a setTimeout.

You can put this in a function and simply keep recalling the function:
function askAge(){
var dateage = prompt("How old are you?");
if(dateage >= 14){
dateage = dateage/2 + 7;
alert("The youngest you can date is " + dateage)
} else if(isNaN(dateage)){
alert("Please enter in a number");
askAge();
} else
alert("You're too young to date.");
}
askAge();

wrap the question and output in a while loop, breaking only when number has been entered

Personally, I like to have "restartable" functions look like:
(function() {
var restart = arguments.callee; // "magic" property refers to current function
if( somecondition) setTimeout(restart,1);
else {
// do actual stuff
}
})();
The setTimeout released the current call stack, otherwise you could potentially get a stack overflow error if you manage to infinitely loop restart.

function checkAge() {
var dateage = prompt("How old are you?");
if(dateage >= 14){
dateage = dateage/2 + 7;
alert("The youngest you can date is " + dateage)
} else if(isNaN(dateage)){
if (confirm("Please enter in a number")) checkAge();
} else
alert("You're too young to date.");
}
checkAge();

Related

Guessing game, 1 to 100 using do/while loop and if/ese if conditional statement

I am trying to make a guessing game with simple java script. the professor gave us a guide, but i am still a bit confused. Based on the guide, we are to use a do/while loop, and within that loop, use the if/else if conditional statement, here is what i have so far.
i've tried changing it so many times, and all i end up with is a never ending loop, even after the number is guessed, it doesnt stop
<body>
<p>
I'm thinking of a number between 1 and 100, try to guess it! </br>
<script>
var number = Math.floor(Math.random() * 100 + 1)
//guess variable to store the guessed number by user
var guess
//output to store output to the user
var output
//if the user guessed the number or not, initialize it to false
var guessed = false
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt ("Think of a number between 1 and 100, what is your number?");
document.write ("You guessed the number " + guess + "<br/>");
if (guess > number) {
document.write ("You guessed too high, think smaller" + "<br/>");
guessed = false
}
else if (guess < number){
document.write ("You guessed too low, think bigger" + "<br/");
guessed = false
}
else {
alert("You guessed the right number!")
guessed = true}
}
while (guessed = false)
</script>
</p>
</body>
You're missing a ton of semi-colons which should be added though your code will still run without them. And like everyone else said you are assigning guessed to false at the end of your do while loop, therefore it will never break out. To check a condition you should use 3 equal signs (this is strict comparison). More on that here. It is debatable if document.write should be used. Reason for that can be found here. Also, when testing your code it worked intermittently, so I added a div with the id of hints. Then I grabbed that element with var elHints = document.getElementById('#hints'); Then to add content to the element hints simply do elHints.textContent += .... The plus equals (+=) adds content to the element without overwriting existing content. In css I added a style to #hints: white-space: pre-line; this allows line breaks (\n) to the div when adding content using textContent. More on that here.
Here is the full javascript code:
var number = Math.floor(Math.random() * 100 + 1);
//guess variable to store the guessed number by user
var guess;
//output to store output to the user
var output;
//if the user guessed the number or not, initialize it to false
var guessed = false;
var elHints = document.getElementById('hints');
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt("Think of a number between 1 and 100, what is your number?");
elHints.textContent += "You guessed the number " + guess + '\n';
if (guess > number) {
elHints.textContent += "You guessed too high, think smaller" + '\n';
guessed = false;
} else if (guess < number) {
elHints.textContent += "You guessed too low, think bigger" + '\n';
guessed = false;
} else {
alert("You guessed the right number!")
guessed = true;
}
}
while (guessed === false);
And here's the jsfiddle.
I believe that you are missing a semi-colon here :
while(guessed == false);
This is just an requirement specific to the do-while loop and does not occur in the syntax for other loops.
In your condition at while(guessed = false) you use one equal-signe (=), witch is forever true. you must write (guessed == false) or (guessed === false). for trying i would do ist so:
I'm thinking of a number between 1 and 100, try to guess it!
<script type="text/javascript">
var number = Math.floor(Math.random() * 100 + 1);
// Just for Test
document.getElementById('test').innerHTML += '<br />' + number;
//guess variable to store the guessed number by user
var guess;
//output to store output to the user
var output;
//if the user guessed the number or not, initialize it to false
var guessed = false;
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt("Think of a number between 1 and 100, what is your number?");
document.getElementById('test').innerHTML += '<br />' + "You guessed the number " + guess;
if (guess > number) {
document.getElementById('test').innerHTML += '<br />' + "You guessed too high, think smaller";
guessed = false;
}
else if (guess < number) {
document.getElementById('test').innerHTML += '<br />' + "You guessed too low, think bigger";
guessed = false;
}
else {
alert("You guessed the right number!")
guessed = true;
}
}
while (guessed == false)
</script>
Your code has some issues.
First of all you need to change while (guessed = false) into while (guessed === false) because it should be a comparision, hence you have to use a comparator.
Secondly, you are using document.write(). This will not work, because the HTML won't change until the user breaks out of the loop. It would be a good idea to use alert() instead. Here is a working example:
var number = Math.floor(Math.random() * 100 + 1)
//guess variable to store the guessed number by user
var guess
//output to store output to the user
var output
//if the user guessed the number or not, initialize it to false
var guessed = false
//do/while loop, while condition is based on if the user NOT guessing the number (e.g. guessed == false)
do {
guess = prompt("Think of a number between 1 and 100, what is your number?");
if (guess > number) {
alert("You guessed too high, think smaller");
guessed = false
} else if (guess < number) {
alert("You guessed too low, think bigger");
guessed = false
} else {
alert("You guessed the right number!")
guessed = true
}
}
while (guessed === false)

Syntax error resulting from invalid syntax in if / else statements

// Check if the user is ready to play!
confirm("Are you ready to play?");
var age = prompt("What's your age");
if ( age is less than 13)
{
console.log("You are allowed to play,but we take no responsibility");
}
else {
console.log("Go on! you can play");
}
I've got a syntax error while executing this JavaScript code, the first two lines (confirm and variable) are correct, this error is somewhere in the if / else satements.
Use < operator instead of is less than
// Check if the user is ready to play!
confirm("Are you ready to play?");
var age = prompt("What's your age");
if (age < 13) {
alert("You are allowed to play, but we take no responsibility");
} else {
alert("Go on! you can play");
}
You can reduce line of code also by using ternary operator
age < 13 ? console.log("You are allowed to play, but we take no responsibility"):console.log("Go on! you can play");

JAVASCRIPT HELP - code not working

My code isn't working, can someone please tell me what the problem is?
I'm guessing it's the for loop, but I cannot find the problem.
<html>
<body>
<script>
username = prompt("Please enter a your username:");
for (var i = 0; i < username; i++) {
if(isFinite(username.charAt(i))) {
result = true;
document.write("The username consists of one or more numbers." + BR);
}
else {
result = false;
document.write("The username must consist of one or more numbers." + BR);
}
}
</script>
</body>
</html>
You have two problems in your code:
In the for loop, use the length of the variable to establish the stop condition
for (var i = 0; i < username.length; i++)
BR is not defined
Working code: http://jsfiddle.net/f643fr4w/
From the output I can probably assume you just want to check if username consists of at least one number, actually: a digit.
// iterate over the input
for (var i = 0; i < username.length; i++) {
// check if it is a number (not a digit but that's the same here)
if (isFinite(username.charAt(i))) {
result = true;
// The requirement "one or more numbers" is fulfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
// print something according to "result"
if(result === true){
document.write('The username consists of one or more numbers.');
} else {
document.write('The username must consist of one or more numbers.');
}
}
You have to go over the full length of the string to find out if there's no number but not if you want to find out if there is any number in it.
Now, if you want to test if it consists of only digits you have to reword the requirements, they are a bit too ambiguous now.
Additional hints:
you need to check the input, you always have to check user input!
you need to be aware that JavaScript strings are UTF16. Rarely a problem but gets easily one if you iterate over JavaScript strings.
String.charAt() returns a character, not a number. Don't rely on the automatic conversions in JavaScript, you way too easily shoot yourself in the foot if you rely on it but also if you don't, so be careful.
please don't use document.write, use either the console if available or change the text-node of an HTML element.
With these points in mind you may get something like this:
// make a list of digits
var digits = ['0','1','2','3','4','5','6','7','8','9'];
// ask the user for a username
var username = prompt("Please enter a your username:");
// check input
if (username.length === 0) {
console.log('no username given');
} else {
for (var i = 0; i < username.length; i++) {
// indexOf searches for the same type, that's why the digits above
// are strings with quotes around them
if (digits.indexOf(username.charAt(i)) >= 0) {
result = true;
// The requirement "one or more numbers" is fullfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
}
// print something according to "result"
if (result === true) {
console.log('The username consists of one or more numbers.');
} else {
console.log('The username must consist of one or more numbers.');
}
}
The above is one variation of many and could easily give rise to a heated discussion on some forums (not here! Of course not! ;-) ) but I hope it helps.
Use a regex for such shenanigans:
var username = prompt("username plz kk thx");
var result = /[0-9]/.test(username);
document.write("The username " + (result ? "consists" : "must consist") + " of one or more numbers");

Need some advice on a Javascript number guessing game

this is my first post ever so go easy on me haha! I'm working on a number game that prompts a user to guess a random number between 1 and 100. The part I'm having trouble with is telling a user if they previously already guessed a number. I've been playing around with it myself and for example if I submit 10, and then 10 again it will say that I repeated a guess (which is what it should do). If I say 10 for a third time it doesn't tell me that I've repeated a guess and rather that the number is too low (it should just say that I've repeated the guess again). Here's the jsfiddle for clarification: https://jsfiddle.net/k1d8awf6/2/.
var random = Math.ceil(Math.random()*100);
var guessList = new Array();
var guess = prompt("Hello user, I'm thinking of a number between 1-100. What is it?");
guessList.push(guess);
while (guess != random) {
for (i = 0; i < guessList.length-1; i++) {
if (guess == guessList[i]) {
guess = prompt("You already guessed this number. Try again.");
}
}
if (guess > random) {
guess = prompt("Your guess is too high! Try again.");
guessList.push(guess);
}
if (guess < random) {
guess = prompt("Your guess is too low! Try again.");
guessList.push(guess);
}
if (guess == random) {
alert("Nice job! You guessed the correct number! It took you " + guessList.length + " tries!");
}
}
You're doing if's, when you should be doing else if's. In addition, you can use the indexOf function instead of looping through elements. eg:
var random = Math.ceil(Math.random()*100);
var guessList = new Array();
var guess = prompt("Hello user, I'm thinking of a number between 1-100. What is it?");
while (guess != random) {
if (!guess) {
// The user cancelled or entered 0, just cancel the game
return;
} else if (guessList.indexOf(guess) >= 0) {
// User already guessed this number
guess = prompt("You already guessed this number. Try again.");
} else {
// User hasn't guessed this number, store their guess then display whether they're too high or too low
guessList.push(guess);
if (guess > random) {
guess = prompt("Your guess is too high! Try again.");
} else if (guess < random) {
guess = prompt("Your guess is too low! Try again.");
}
}
}
// The guess is correct when we exit the loop
alert("Nice job! You guessed the correct number! It took you " + (guessList.length + 1) + " tries!");
More info on indexOf: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
You may also want to end the game if the user enters '0' or Cancels the dialog :)
Edit
Edited to fix some logic errors, updated fiddle here: https://jsfiddle.net/k1d8awf6/8/

Use only the first number generated with Math.random

I'm a student creating a 3-guess game with JavaScript. My game doesn't work properly, I believe Math.random is generating a new number at every stage of the game. I would be most grateful if somebody helps me define a single number for the variable randomNumber.
Here's the JavaScript:
function game()
{
var randomNumber = Math.floor(Math.random()*11);
var userGuess = prompt ("Guess what number I'm thinking of? (It's between 0 & 10)");
if (userGuess === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
var userGuess2 = prompt ("Dohhh! You got it wrong. You have 2 more chances.");
}
if (userGuess2 === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
var userGuess3 = prompt ("Dohhh! You got it wrong. You have 1 more chance.");
}
if (userGuess3 === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
alert ("Bad luck. The number was: " + randomNumber);
}
}
prompt returns a string. You are using the strict equality operator, ===, to compare strings with numbers. They will never be equal.
Use the abstract equality operator, ==, or convert the strings to numbers before comparing with the strict equality operator.
Also, your function should probably return after a correct guess, rather than prompting for more guesses.
Here's a suggestion for a cleaned-up version of your code:
function playGame(guesses)
{
// By default, give the player 3 guesses.
guesses = guesses || 3;
var randomNumber = Math.floor(Math.random()*11);
var userGuess = prompt("Guess what number I'm thinking of? (It's between 0 & 10)");
// Repeat the following logic whenever the user guesses incorrectly.
while (userGuess !== randomNumber.toString())
{
--guesses;
if (guesses === 0)
{
alert("Bad luck. The number was: " + randomNumber);
return false;
}
userGuess = prompt("Dohhh! You got it wrong. You have " + guesses + " more chance(s).");
}
alert("Good Guess, you must be psychic!");
return true;
}
Notice that it's now more flexible (you can give the user a configurable number of guesses) while also reducing code duplication: instead of repeating the same block of logic (with small differences), there is really just one bit of logic that can be repeated as many times as you like.

Categories

Resources