Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I built a simple number guessing game with javascript.
After the computer guess the correct answer it should break the loop.
What I am wondering is that even though I break the loop at Line 18
It still execute the code on Line 20(console.log(text)).
The funny thing is that after the break. Only console.log() get executed,L21 & L22 don't do anything,which they are supposed to be that way.
Can't really figure out why. I hope I make the question clear!
Executes last console.log() in repl example
But doesn't in the below snippet (the exact same code)..
let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (true){
let text = `#${i}: computer guess ${guess}.`
if (guess > answer){
text += 'TOO BIG!'
max = guess
} else if (guess < answer){
text += 'TOO Small!'
min = guess
} else{
text += 'win!'
break
}
console.log(text)
guess = Math.floor((max + min) / 2)
i++
}
My guess is that because the REPL tool tries to display a return value for the code you run, it's using the last value before the code exits, which is text += "win!". So it's not actually executing your console.log(text), it just looks like it is.
For example, if you change your code to the following, the REPL tool spits out a number (the value of i before the postfix). Because it's the last value it saw before the while loop exited.
REPL example showing a different "return" value, logging as expected
let answer = Math.floor(Math.random() * 100) + 1
// start coding
console.log('Answer is ' + answer)
let max = 100
let min = 0
let guess = Math.floor((max + min) / 2)
let i = 1
while (guess !== answer){
let text = `#${i}: computer guess ${guess}.`
if (guess > answer){
text += 'TOO BIG!'
max = guess
} else if (guess < answer){
text += 'TOO Small!'
min = guess
}
console.log(text)
guess = Math.floor((max + min) / 2)
i++
}
// console.log(`#${i}: computer guess ${guess}. Win!`);
This is not normal JS behavior, and should be taken with a grain of salt when reading "return" values in the REPL tool.Hope this helps!
Related
This question already has answers here:
Masking credit card number
(5 answers)
Closed 12 months ago.
I got the below coding assessment question in Javascript. I tried my best to solve but there are few edge cases I missed. I need help to identify those missing cases
Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct.
However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.
This is what I tried so far
function maskify (cc) {
if (cc.length < 6) {
let reversed = reverse(cc);
let newString = '';
for (let i = 0; i < reversed.length; i++) {
if (i < 4) {
newString += reversed[i];
} else {
newString += '#';
}
}
return reverse(newString);
Output
This is my solution:
function maskify (cc) {
// If less than 6 characters return full number
if (cc.length < 6)
return cc;
// Take out first character
let firstChar = cc.charAt(0);
cc = cc.slice(1);
// Replace characters except last 4
cc = cc.replace(/\d(?=.{4,}$)/g, '#');
// Add first character back
cc = firstChar + cc;
return cc;
}
// Run every example number
const tests = ["4556364607935616", "4556-3646-0793-5616",
"64607935616", "ABCD-EFGH-IJKLM-NOPQ",
"A1234567BCDEFG89HI", "12345", "", "Skippy"];
tests.forEach((number) => console.log(`Testing: ${number} - Output: ${maskify(number)}`));
I ran it with all the numbers of your example and it gets the correct output.
Hi I need a block of code for some math that I'm trying to work out. The code I'm looking for will be able to add half a percent (0.005) to a number and return the result back to me. I need the code to take two separate inputs, the first is the start number, and the second is how many times I want the loop to execute. An example would be if I started with 7000 the code should output ~7321.37 (if possible let it stop after 2 decimal points). Thank you for the help in advance!
Code example of what I'm trying to do:
function growth(initialValue, timesOfExecution)` {
let answer;
let execute;
while (execute > 0) {
answer = initialValue + initialValue(0.05)
execute--
}
return answer;
}
console.log(growth(7000, 9))
Here you go:
function growth(initialValue, timesOfExecution) {
for (let i = 0; i < timesOfExecution; i++) {
initialValue = initialValue + (initialValue * 0.005)
}
return initialValue.toFixed(2);
}
console.log(growth(7000, 9))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How can i fix this issue where the alerted Encrypted value is NaN?
function Encrypt() {
var Plaintext = document.getElementById("txt").value;
var Key = Math.floor(Math.random() * 26) + 1;
var Chaesarshifted = caesarShift(Plaintext,Key);//i just didn't paste Chaesarshift code
var Encrypted;
alert(Chaesarshifted);
for (let index = 0; index < Chaesarshifted.length; index++) {
Chaesarshifted.toLowerCase();
//till here everything works fine
Encrypted += Chaesarshifted.charCodeAt(index) - 96;
}
alert(Encrypted);// Alert says NaN
}
The initial value of Encrypted is not set. So when you are trying to += to it, it doesn't know how to handle that operation.
You should prime Encrypted to the empty string "" for the starting value.
Then, inside the for loop, Chaesarshifted.toLowerCase(); does not set the value, but must be stored.
Also, your logic is off to append the Encrypted text. You need to change the character back into a unicode character. Or possibly even build an array to concatenate later.
Finally, you should start your variable names with a lowercase to follow convention.
To put it all together:
function Encrypt() {
var plaintext = document.getElementById("txt").value;
var key = Math.floor(Math.random() * 26) + 1;
var chaesarshifted = caesarShift(plaintext,Key); //missing chaesarshift code
var encrypted = "";
alert(chaesarshifted);
chaesarshifted = chaesarshifted.toLowerCase();
for (let index = 0; index < chaesarshifted.length; index++) {
//missing code
encrypted += String.fromCharCode(chaesarshifted.charCodeAt(index) - 96);
}
alert(encrypted);// Alert will show garbled text (offset values from chaesarshift str)
}
Edit: Thanks to Barmar's comment to get me thinking about the problem more.
I am working on writing code for a course and need to figure out why the code output is not executing properly. I am very new to coding, this is a beginner assignment so all help and explanations are greatly appreciated.
The output should look like this:
Output:
How many times to repeat? 2
Stats Solver execution 1 ====================
give a number 10.10203
give a number 20
give a number 30
give a number 40
give a number 50
sum: 150.10203
average: 30.020406
max: 50
min: 10.10203
ratio: 4.94
Stats Solver execution 2 ====================
give a number 3.21
give a number 2.1
give a number 1
give a number 5.4321
give a number 4.321
sum: 16.0631
average: 3.21262
max: 5.4321
min: 1
ratio: 5.43
done ====================
Here is the code:
"use strict";
function myMain() {
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
}
function wall(){
var num1 = Number(prompt("provide a number"));
var num2 = Number(prompt("provide a second number"));
var num3 = Number(prompt("provide a third number"));
var num4 = Number(prompt("provide a fourth number"));
var num5 = Number(prompt("provide a fifth number"));
var sum = (num1+num2+num3+num4+num5);
alert("sum: " + sum);
var avg = (sum/5);
alert("average: " + avg);
var max = (Math.max(num1,num2,num3,num4,num5));
alert("max: " + max);
var min = (Math.min(num1,num2,num3,num4,num5));
alert("min: " + min);
var ratio = (max/min);
alert("ratio: " + Math.floor(ratio*100)/100);
}
myMain();
Well you really aren't very far off at all. Actually your solution has all the code you need just some of it is in the wrong place. I would have posted this as a comment but as this is a new work account I can't actually post comments so here is a full solution with the explanations.
Your wall function, while annoying with all the alerts is actually correct and doesn't need any adjustments. With that said you might want to play with parseInt and parseFloat to make sure you are getting valid numbers but I am assuming that is outside of the scope of the assignment.
Now on to your main function.
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
This is ok and will prompt the user for a number, once again you might want to test that you got a valid number using the aforementioned links.
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This is where things start to fall apart a bit and where i think you are having problems. So I will break this down line for line and explain what each line is doing and you can compare that to what you think its doing.
var count = num;
Nothing crazy here, you are just creating another variable to hold the value in the num variable. Slightly redundant but not really a big deal.
for (var a=0; a<=num; a++) {count++;}
This is the line that appears to have given you the most confusion. This is the actual loop but inside the body of the loop { .... } nothing is being done except 1 is being added to count (count++). If I am understanding the assignment correctly, inside this loop is where you need to call your wall function after alerting the 'Stats Solver execution .....' stuff. All you need to do is move your function call inside this loop.
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This part is clearly you a little lost and just trying things to get it to work, don't worry even after 12+ years of development i still write code like this ;). You really don't need this as the actual call to wall() will work fine for you.
I am bored and am waiting on work so for the sake of being a complete answer here is an example of how your code should look. Please don't just hand this in rather try and actually understand the difference between what i wrote and what you did because these are some very basic concepts that if you gloss over will make your life much harder down the road. Always feel free to ask, thats how people learn.
function myMain(){
// get the number of repetitions from the user and cast as a number
var num = Number(prompt('Please enter the number of times to repeat'));
// loop from 0 to the number the user provided - 1 hence the <
for (var i = 0; i < num; i++){
// alert the iteration of the loop, you will notice i add 1 to num when we alert it; this is because it starts at 0 so the first time it displays it would show 'Stats Solver execution 0 ======' instead of 'Stats Solver execution 1 ======'
alert('Stats Solver execution ' + (num + 1) + ' ===============');
// call your wall function
wall();
// go back to the top of the loop
}
// alert that we are done.
alert('done===============')
}
// your wall function goes here
// call your myMain function to kick everything off
myMain();
Just for fun you might want to look at console.log instead of alert to not make it such an annoying process with all the popups.
If i missed anything or you are confused about anything don't hesitate to ask and i'll do my best to answer.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
var userweight = prompt ("What is your weight?");
var userheight = prompt ("What is your height in meter?");
var bmi = function (userweight,userheight){
return userweight/(userheight*userheight);
};
var bmi= function(calc){
if(calc<=18.4){
return("you are thin");
}
else if (18.5<=calc<=24.9){
return("you are normal");
}
else if (25.0<=calc<=29.9){
return("you are fat");
}
else if (calc>=30.0){
return("you have obesity");
}
};
bmi(userweight,userheight);
I tried to make a bmi calculator. It calculates your bmi . But it had problems in if/else part. It only shows "You are normal" no matter what bmi it is
At the first, you override the first bmi-formula function assignment with your if/else statements.
You should rename one of these functions:
var userweight = prompt("What is your weight?");
var userheight = prompt("What is your height in meter?");
var formula = function(userweight,userheight){
return userweight / (userheight * userheight);
};
var bmi = function(userweight, userheight){
var calc = formula(userweight, userheight);
if (calc <= 18.4) {
return "you are thin";
}
if (calc >= 18.5 && calc <= 24.9) {
return "you are normal";
}
if (calc >= 25.0 && calc <= 29.9) {
return "you are fat";
}
if (calc >= 30.0) {
return "you have obesity";
}
};
alert( bmi(userweight, userheight) );
The second thing is, that your condition to return the "normal"-part (18.5<=calc<=24.9) is falsey, you could do it like this: calc >= 18.5 && calc <= 24.9. (The same for the "fat"-part)
The last note, as you can see, I've removed the else-keywords since we return a value after if, it doesn't matter what then comes.
You declare the bmi function expression
var bmi = function (userweight,userheight){
return userweight/(userheight*userheight);
};
but the subsequent declaration later on overwrites it completely. So when you call
bmi(userweight, userheight)
Javascript takes the passed in userweight and assigns it to calc. The BMI isn't calculated at all, your first function is never called.
userheight is never used; JavaScript doesn't care if you pass in too many arguments.
Give your functions different names e.g. renaming your first function to calculateBMI and the second one to adviseOnBMI (or whatever you fancy) and rerun it.
console.log is your friend when debugging - use it to output to the Developer Console in your browser of choice.