Javascript (break) - javascript

Im in the process of learning javascript and I cant seem to understand why the break statement isnt functioning :( Can someone please tell me what I've done wrong?
let maximum = parseInt(prompt("Enter the maximum number"));
while(!maximum){
maximum = parseInt(prompt("Enter a valid number"));
}
const randomNum = Math.floor(Math.random() * maximum) + 1;
console.log(randomNum);
let guess = parseInt(prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`));
let attempts = 1;
while (parseInt(guess) !== randomNum){
if (guess === 'q') break;
attempts++;
if(guess > randomNum){
guess = prompt("Too high, guess again.");
} else{
guess = prompt("Too low, guess again.");
}
}
if (guess === 'q'){
console.log("Quitting.")
} else {
console.log(`It took you ${attempts} amounts of guesses!`)
}

if (guess === 'q')
You are parsing the value to an integer and are comparing it to a string. Which is always false
So when you type 'q' in your prompt and try parseInt on it you will get NaN which stands for not a number. And NaN is not equal with q obviously
EDIT:
as #axic correctly pointed out the condition from above cannot be fulfilled if q was typed before the iteration begins. But that brings another problem:
On the third iteration you will get another prompt saying "Too low, guess again." even if you guessed the right number, because guess is string and compared to a number which will return false in all cases.

You are parsing the value to an integer and are comparing it to a string.
let maximum = parseInt(prompt("Enter the maximum number"));
while (!maximum) {
maximum = parseInt(prompt("Enter a valid number"));
}
const randomNum = Math.floor(Math.random() * maximum) + 1;
console.log(randomNum);
let guess = prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`);
let attempts = 1;
while (parseInt(guess) !== randomNum) {
if (guess === 'q') break;
attempts++;
if (guess > randomNum) {
guess = prompt("Too high, guess again.");
} else {
guess = prompt("Too low, guess again.");
}
}
if (guess === 'q') {
console.log("Quitting.")
} else {
console.log(`It took you ${attempts} amounts of guesses!`)
}

The break statement works totally fine, the issue is in a different location of your logic. You are parsing the integer of guess when displaying the first prompt to enter a guess for the number but when entering anything that isn't a number the value will simply be NaN.
Line 7 is:
let guess = parseInt(prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`));
but should be:
let guess = prompt(`Enter your guess for the generated number between 1 and the maximum number of ${maximum}.`);
I'm not entirely sure if this is what you want to achieve but based on the little information you gave I assumed that this would be what you're trying to get.

Related

Is it possible to have more than one var in a do-while cycle?

Is it possible something like this or should I split my cycle into two distinct do-while cycles?
Because it doesn't work, it only appears once and stops, when my mission is to continually ask the number and odd or even to the user until he gives them to me. My question was about the possibility to execute two different var in one single do in a do-while cycle
//Data
var userWord;
var userNumber;
// The user choose between odd or even a number between 1 and 5.
do {
userWord = prompt("Choose odd or even");
userNumber = parseInt(prompt("Give me a number between 1 and 5"));
} while (userWord.length == 0 && userNumber == 0);
The condition in the while in my mind is "if the value you put is 0, so nothing, then the question is asked again until you write somenthing.
You need to use ||, not &&. This is true when any of the sub-conditions are true. Your condition will only be true when all of the sub-conditions are true.
var userWord;
var userNumber;
// The user choose between odd or even a number between 1 and 5.
do {
userWord = prompt("Choose odd or even");
userNumber = parseInt(prompt("Give me a number between 1 and 5"));
} while (userWord.length == 0 || userNumber < 1 || userNumber > 5);
console.log(userWord, userNumber);
It would be nicer for the user if you had separate loops for each input, so they don't have to re-enter both when they get one of them wrong.
var userWord;
var userNumber;
do {
userWord = prompt("Choose odd or even");
} while (userWord.length == 0);
do {
userNumber = parseInt(prompt("Give me a number between 1 and 5"));
} while (userNumber < 1 || userNumber > 5)
console.log(userWord, userNumber);

Guess the number – creating number range JavaScript

I am currently trying to create a Guess the Number game using Javascript. I have set the code to display a different output depending on the number entered.
However, I would like to add range to this. For example, if the guess is within 10, above or below, the output should read "Almost". However, if the user is out of this range, it should read something different.
What operation should I use? Currently I'm just using:
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Your guess is out by 10 – please guess again!';
But this doesn't reflect the range as I'd like it to.
you can use absolute value to get the distance between the userGuess and the randomNumber
you can get it with Math.abs
const randomNumber = 4 // chosen by fair dice roll.
// guaranteed to be random.
let userGuesses = [42, -15, 2]
for (let guess of userGuesses) {
if (Math.abs(guess - randomNumber) <= 5) {
// the guess is in the range [random - 5; random + 5]
console.log(`guess ${guess} is very close`)
} else if (Math.abs(guess - randomNumber) <= 20) {
// the guess is in the range [random - 20; random + 20]
console.log(`guess ${guess} is not that far`)
} else {
console.log(`guess ${guess} is pretty far`)
}
}
as you can see it works if you're under the wanted number or over it
You should check if the difference between guessed number and random number is within range of 10.
var difference = Math.abs(userGuess - randomNumber);
if(difference > 10) {
lowOrHi.textContent = 'Your guess is out by 10 – please guess again!';
} else {
lowOrHi.textContent = 'Your guess is almost correct!';
}
Try the following
if((userGuess-randomNumber)<-10||(userGuess-randomNumber)>10) {
console.log('Your guess is out by 10 – please guess again!');}
else {
console.log("Almost");
}

Random number is not staying within range javascript [duplicate]

This question already has an answer here:
Javascript Addition wont work
(1 answer)
Closed 5 years ago.
I have made a Random Number Guess game. The user has to set the minimum and maximum range the random number can be generated in and the number of attempts they get changes dependent on the size of the range they have set. So if the user enters in a minimum of 1 and a maximum of 100 the range will be divided by 10 and rounded up to give the user 10 attempts to guess the number.
The problem I have is that the random number being generated is always way out of the set range and I am not sure why.
My javascript code:
winner = "Well done, you guessed the number correctly";
loser = "Unfortunately you did not guess the number correctly. Game Over!";
higher = "Your guess was too low. Guess higher";
alreadyWon = "You have already guessed correctly. Press f5 to play again";
lower = "Your guess was too high. Guess lower";
gameWon = false;
counter = 0;
function processingFunction(minRange, maxRange) {
randomNo = Math.floor(Math.random() * (maxRange - minRange)) + minRange; //random number generated
attempts = Math.round((maxRange - minRange) / 10); //number of attempts generated
return (randomNo, attempts);
}
function showFunction(guess) {
if (gameWon == true) {
document.getElementById("output1").innerHTML = alreadyWon;
} else if (counter < attempts) {
if (guess == randomNo) {
document.getElementById("output1").innerHTML = winner;
gameWon = true;
} else if (guess > randomNo) {
document.getElementById("output1").innerHTML = lower;
} else {
document.getElementById("output1").innerHTML = higher;
}
counter++;
} else {
document.getElementById("output1").innerHTML = loser;
}
}
<center>
<h2>Random Number Guess</h2>
</center>
<h3>Enter in the minimum range and the maximum range. Accompanied by your first guess</h3>
Minimum Range:<input type="text" id="inputMinRange"></input> Maximum Range:<input type="text" id="inputMaxRange"></input>
<button type="button" onclick="processingFunction(document.getElementById('inputMinRange').value, document.getElementById('inputMaxRange').value)">Set Range</button>
<br><br>
<input type="text" id="guessInput"></input>
<button type="button" onclick="showFunction(document.getElementById('guessInput').value)">Guess</button>
<pre type="text" id="output1"></pre>
The value of an input is always a string, and when you use + where one of the operands is a string, you get string concatenation, not addition. (- will coerce to number, but + will not.) So say we fill in 1 and 100. This:
randomNo = Math.floor(Math.random() * (maxRange - minRange)) + minRange; //random number generated
...takes maxRange - minRange and gets 99 (so far so good), multiplies that by a random value to get (say) 83, and then appends "1" to it to get "831".
You want to convert those values to numbers before feeding them into the function. There are lots of ways to do that (see this answer for a rundown of them, but for instance, the unary +:
<button type="button" onclick="processingFunction(+document.getElementById('inputMinRange').value, +document.getElementById('inputMaxRange').value)">Set Range</button>
<!-- ---------------------------------------------^------------------------------------------------^ -->
Now the function is working with numbers throughout.
Updated snippet:
winner = "Well done, you guessed the number correctly";
loser = "Unfortunately you did not guess the number correctly. Game Over!";
higher = "Your guess was too low. Guess higher";
alreadyWon = "You have already guessed correctly. Press f5 to play again";
lower = "Your guess was too high. Guess lower";
gameWon = false;
counter = 0;
function processingFunction(minRange, maxRange) {
randomNo = Math.floor(Math.random() * (maxRange - minRange)) + minRange; //random number generated
attempts = Math.round((maxRange - minRange) / 10); //number of attempts generated
console.log(minRange, maxRange, randomNo, attempts);
return (randomNo, attempts);
}
function showFunction(guess) {
if (gameWon == true) {
document.getElementById("output1").innerHTML = alreadyWon;
} else if (counter < attempts) {
if (guess == randomNo) {
document.getElementById("output1").innerHTML = winner;
gameWon = true;
} else if (guess > randomNo) {
document.getElementById("output1").innerHTML = lower;
} else {
document.getElementById("output1").innerHTML = higher;
}
counter++;
} else {
document.getElementById("output1").innerHTML = loser;
}
}
<center>
<h2>Random Number Guess</h2>
</center>
<h3>Enter in the minimum range and the maximum range. Accompanied by your first guess</h3>
Minimum Range:<input type="text" id="inputMinRange"></input> Maximum Range:<input type="text" id="inputMaxRange"></input>
<button type="button" onclick="processingFunction(+document.getElementById('inputMinRange').value, +document.getElementById('inputMaxRange').value)">Set Range</button>
<br><br>
<input type="text" id="guessInput"></input>
<button type="button" onclick="showFunction(document.getElementById('guessInput').value)">Guess</button>
<pre type="text" id="output1"></pre>
use below code to convert you are passing a string and + will append the minRange string with generated random no.
randomNo = Math.floor(Math.random() * (maxRange - minRange))+Math.round(minRange);
or
randomNo = Math.floor(Math.random() * (maxRange - minRange))-(-minRange);

Plus equals operator error

Hello so I'm trying to get the += to increase value of balance. I now understand that in java script use += is to pass by reference, but how can I use it to pass by value.
alert("Welcome to the Online Bank Teller");
var balance = 100.00;
var amount;
var run = true;
do{
var pick = prompt("Make a selection...\n1-Check Balance, 2-Deposit, 3-Withdraw, 4-Quit");
if(pick == 1){alert("Your balance is: $" + balance.toFixed(2));}
else if(pick == 2){
amount = prompt("Enter the amount you want to deposit: $");
if(amount > 1000){alert("You can only enter up to $1000 per deposit!");}
Right here--->balance += amount;
alert("Your new balance: $" + balance.toFixed(2));
}
else if(pick == 3){
amount = prompt("Enter the amount you want to withdraw: $");
if(amount > balance){alert("Amount exceeded account balance!");}
else if(amount > 500){alert("The max you can take out is up to $500 per withdraw!");}
else if (amount <= balance){
balance -= amount;
alert("Your new balance: $" + balance.toFixed(2));
}
}
else if(pick == 4){run = false;}
else{alert("Not a valid choice!");}
}while(run)
How can I get it to alter the value inside of the variable when the user enters a new deposit.
I get
Your balance is: $10022
instead of
Your balance is: $122
Thanks in advance...
use parseInt() function to each amount which is getting from prompt
amount = parseInt(prompt("Enter the amount you want to deposit: $"), 10);
DEMO
Try
balance = parseInt(balance) += parseInt(amount);
Balance and amount are strings, so for example:
Adding the string '50' to the string of '3' woul make '503'
Adding the float value of '50' to the float value of '3' would make '53'
As an alternative to the parseInt function that has already been mentioned, there are some "quick&dirty" ways to do it:
amount = 1 * prompt("Enter the amount you want to deposit: $");
// get'S converted because * is only defined on numbers
amount = +prompt("Enter the amount you want to deposit: $");
// converted because unary + is only defined on numbers
and a couple of other, less common ones.
Adding a string to a number with += operator produces a string.
prompt() returns a string, hence you need to convert the return values to a number:
balance += +amount;
Or use parseFloat() to convert values. Though I can't understand how you'd get anything alerted, since strings haven't toFixed() method, and hence the alert() in your code is supposed to trigger an error.

Advice on how to code Luhn Credit Card validation with Javascript?

I'm pretty awful at Javascript as I've just started learning.
I'm doing a Luhn check for a 16-digit credit card.
It's driving me nuts and I'd just appreciate if someone looked over it and could give me some help.
<script>
var creditNum;
var valid = new Boolean(true);
creditNum = prompt("Enter your credit card number: ");
if((creditNum==null)||(creditNum=="")){
valid = false;
alert("Invalid Number!\nThere was no input.");
}else if(creditNum.length!=16){
valid = false;
alert("Invalid Number!\nThe number is the wrong length.");
}
//Luhn check
var c;
var digitOne;
var digitTwo;
var numSum;
for(i=0;i<16;i+2){
c = creditNum.slice(i,i+1);
if(c.length==2){
digitOne = c.slice(0,1);
digitTwo = c.slice(1,2);
numSum = numSum + (digitOne + digitTwo);
}else{
numSum = numSum + c;
}
}
if((numSum%10)!=0){
alert("Invalid Number!");
}else{
alert("Credit Card Accepted!");
}
</script>
The immediate problem in your code is your for loop. i+2 is not a proper third term. From the context, you're looking for i = i + 2, which you can write in shorthand as i += 2.
It seems your algorithm is "take the 16 digits, turn them into 8 pairs, add them together, and see if the sum is divisible by 10". If that's the case, you can massively simplify your loop - you never need to look at the tens' place, just the units' place.
Your loop could look like this and do the same thing:
for (i = 1; i < 16; i +=2) {
numSum += +creditNum[i];
}
Also, note that as long as you're dealing with a string, you don't need to slice anything at all - just use array notation to get each character.
I added a + in front of creditNum. One of the issues with javascript is that it will treat a string as a string, so if you have string "1" and string "3" and add them, you'll concatenate and get "13" instead of 4. The plus sign forces the string to be a number, so you'll get the right result.
The third term of the loop is the only blatant bug I see. I don't actually know the Luhn algorithm, so inferred the rest from the context of your code.
EDIT
Well, it would have helped if you had posted what the Luhn algorithm is. Chances are, if you can at least articulate it, you can help us help you code it.
Here's what you want.
// Luhn check
function luhnCheck(sixteenDigitString) {
var numSum = 0;
var value;
for (var i = 0; i < 16; ++i) {
if (i % 2 == 0) {
value = 2 * sixteenDigitString[i];
if (value >= 10) {
value = (Math.floor(value / 10) + value % 10);
}
} else {
value = +sixteenDigitString[i];
}
numSum += value;
}
return (numSum % 10 == 0);
}
alert(luhnCheck("4111111111111111"));
What this does is go through all the numbers, keeping the even indices as they are, but doubling the odd ones. If the doubling is more than nine, the values of the two digits are added together, as per the algorithm stated in wikipedia.
FIDDLE
Note: the number I tested with isn't my credit card number, but it's a well known number you can use that's known to pass a properly coded Luhn verification.
My below solution will work on AmEx also. I submitted it for a code test a while ago. Hope it helps :)
function validateCard(num){
var oddSum = 0;
var evenSum = 0;
var numToString = num.toString().split("");
for(var i = 0; i < numToString.length; i++){
if(i % 2 === 0){
if(numToString[i] * 2 >= 10){
evenSum += ((numToString[i] * 2) - 9 );
} else {
evenSum += numToString[i] * 2;
}
} else {
oddSum += parseInt(numToString[i]);
}
}
return (oddSum + evenSum) % 10 === 0;
}
console.log(validateCard(41111111111111111));
Enjoy - Mitch from https://spangle.com.au
#Spangle, when you're using even and odd here, you're already considering that index 0 is even? So you're doubling the digits at index 0, 2 and so on and not the second position, fourth and so on.. Is that intentional? It's returning inconsistent validations for some cards here compared with another algorithm I'm using. Try for example AmEx's 378282246310005.

Categories

Resources