Treating numbers as strings - javascript

I got bored and decided to make a script, but it isn't working. Instead of adding the numbers, it treats them as strings, ex. 0 + 42 + 0 + 17 would be 042017. Also, the while script goes on forever.
var money = 0;
var yn = false;
var bye = 0;
var add = window.prompt("How many dollars do you want?");
console.log("You got " + add + " dollars!");
parseFloat(add);
money += add;
add = 0;
console.log(money);
while (money < 1000000001 || bye == 1) {
yn = window.confirm("Do you want more money?");
if (yn) {
add = window.prompt("How many dollars do you want?");
console.log("You got " + add + " dollars!");
parseFloat(add);
money += add;
console.log(money);
} else {
console.log("Goodbye!");
bye = 1;
};
};
if (money > 999999999) {
console.log("You won the game with " + money + " dollars!");
};

When you do
parseFloat(add);
it converts add to a floating point value and returns it. Since you are ignoring it, add remains unchanged as a string. You might want to replace the new value in add, like this
add = parseFloat(add);
Also, you can just convert the result of window.prompt itself, like this
add = parseFloat(window.prompt(...));

Most likely the reason your while loop is going on forever is because of the bye variable. Your logic is broken.
If the user answers No to the prompt, bye will be set to 1 and never change back. The while loop will continue as long as bye is 1, so it will go on forever.
To fix this, you can use:
while (money < 1000000001 && bye !== 1) {
or
while (money < 1000000001 || bye === 0) {
However, to store an on/off flag, you should be using a boolean variable, not a number:
var bye = false;
// ....
while (money < 1000000001 && !bye) {
// ....
if (yn) {
// ....
} else {
// ....
bye = true;
}
}
Also note that you don't need (read: shouldn't use) a semicolon after if and while blocks.

Related

Removing alert from code forces it to enter infinite loop

I have a piece of code that has a few window alert messages. It works fine. However, if I remove the alert statements, the program enters into an infinite loop. This is weird for me.
Can someone help me identify the problem with the code?
function countSwaps(arr) {
let notVisited = {}, swaps = 0;
for (let i = 0; i < arr.length; i++) {
notVisited[i] = true;
}
while (Object.keys(notVisited).length) {
alert("main pass");
let nextPos, currentPos = Object.keys(notVisited)[0];
while (arr[currentPos] !== parseInt(currentPos+1)) {
nextPos = arr[currentPos] - 1;
[arr[currentPos], arr[nextPos]] = [arr[nextPos], arr[currentPos]];
swaps+= 1;
alert("Swap " + arr[currentPos] + " and " + arr[nextPos] + "\n");
delete notVisited[nextPos];
}
delete notVisited[currentPos];
}
return swaps;
}
console.log(countSwaps([2,3,4,1,5]));
Well, it runs an infinite loop for me without the alerts as well.
It seems like the problem is the following expression: parseInt(currentPos+1)
The addition happens before the conversion from a string to a number, so for example:
currentPos = '4';
currentPos + 1 == '41';
parseInt(currentPos + 1) == 41
What you want is probably parseInt(currentPos) + 1. Now:
currentPos = '4';
parseInt(currentPos) + 1 == 5
With this the loop seems to quit and I get the result of 3 swaps out of it.
This is cause of infinite loop.
while (Object.keys(notVisited).length)
It should be something like
while (Object.keys(notVisited).length > 0)
That is a property, it will always return true

How to fix this "if" statement

I don't really know the correct format to this if statement. I want it to count the frequency each word in my txt file was used.
function countWords(array, word, index) {
var count = 0;
var value = " "
for (var i = 0; i < array.length; i++) {
if (array[i] == 0 && value == word)
count++;
}
}
if (getUserSelectionForm.problem.value == "pay") {
countWords(working2DArray, "pay", 0)
if (getUserSelectionForm.problem.value == "staffing") {
countWords(working2DArray, "staffing", 0)
if (getUserSelectionForm.problem.value == "hours") {
countWords(working2DArray, "hours", 0)
if (getUserSelectionForm.problem.value == "management") {
countWords(working2DArray, "management", 0)
console.log(countWords)
document.getElementById('section2').innerHTML = "The selected word appears " + countWords + " times in the array."
}
Try not to use multiple IF statements and use a switch statement instead. Makes code much clearer and cleaner.
E.g.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
So:
var p = getUserSelectionForm.problem.value;
switch (p) {
case 'pay':
countWords(working2DArray, "pay", 0);
break;
case 'staffing':
countWords(working2DArray, "staffing", 0);
}
You are making three mistakes in code:
You are missing some of the closing curly braces } of you if blocks.
You do not return anything from function. You should return count.
countWords is a function you don't need to display that. You need to display its result.
You can make your code much simpler. You don't need these if statements at all because you are passing the same value of getUserSelectionForm.problem.value to the function so directly pass it.
function countWords(array, word, index) {
var count = 0;
var value= " "
for(var i = 0; i < array.length; i++){
if(array[i] == 0 && value == word)
count++;
}
return count;
}
let word = getUserSelectionForm.problem.value
document.getElementById('section2').innerHTML = `The selected word appears ${countWords(working2DArray,word,0)} times in array`
If you want to only check for few items then use create a array of "pay","staffing"... and use includes() on it
let word = getUserSelectionForm.problem.value
if(["pay","staffing","hours","management"].includes(word)){
document.getElementById('section2').innerHTML = `The selected word appears ${countWords(working2DArray,word,0)} times in array`
}
In my understanding , you want to trigger the function whenever problem.value ==='pay'||'staffing'||'hours'||'management' ,here is clearer version for your reference:
var problemValue = getUserSelectionForm.problem.value;
var isProblemValueMatch = ["pay", "staffing" ,"hours", "management"].includes(problemValue);
if (isProblemValueMatch ) {
var countWords = working2DArray.filter(function(v) {
return v === problemValue;
}).length;
console.log(countWords)
document.getElementById('section2').innerHTML = "The selected word appears " + countWords + " times in the array."
}

Having trouble counting iterations of different outputs in my javascript code

Trying to set up code to take inputted numbers, determine whether they are negative or positive, displaying this, and then when 0 is put in the code displays the amount of positive numbers put in and the amount of negative numbers put in and then terminates. Having trouble with the counting part and I am not sure how to set this up better. I am also not sure how to set this up to terminate after 0 is put in.
function mapping() {
var num = parseInt(document.getElementById("num1").value);
var countp = 0;
var countn = 0;
if (num !== 0) {
if (num > 0) {
document.getElementById("output").innerHTML = "positive";
countp += 1;
} else {
document.getElementById("output").innerHTML = "negative";
countn += 1;
}
} else {
document.getElementById("output").innerHTML = "countp: " + countp;
document.getElementById("output").innerHTML = "countn: " + countn;
}
}
Thank you.
Two problems with the code.
1st: You need to move countp and countn outside of the function to make them global.
2nd: You are writing the positive number counts to output's html and then you are overriding it by negative count.
This should do the trick;
var countp = 0;
var countn = 0;
function mapping() {
var num = parseInt(document.getElementById("num1").value);
if (num !== 0) {
if (num > 0) {
document.getElementById("output").innerHTML = "positive";
countp += 1;
} else {
document.getElementById("output").innerHTML = "negative";
countn += 1;
}
} else {
var html = "countp: " + countp + ", countn: " + countn;
document.getElementById("output").innerHTML = html;
// this line added
countp = 0, countn = 0;
}
}
<input type="text" id="num1">
<button onclick="mapping()">Test</button>
<div id="output">
</div>
The main issue with the code is that countp and countn are local variables. Thus they are created and initialized to 0 every time the function is called. Move the two lines outside the function to fix this bug!
Another bug is the code in the last else part. There you set innerHTML twice, so the div ends up with only countn. To fix this bug, replace the last innerHTML = by innerHTML +=.
Finally, if I understand you correctly, you want that no more updates occur once 0 has been entered. To achieve this, you could add another variable like isFinal that is set to true when the user enters 0, and add a check to your function.
Some more suggestions:
Instead of if (num!==0), it is considered good practice to start with positive conditions such as if (num === 0). That way, you will also avoid some nesting in the conditions.
What happens if the user does not enter a valid number? In your code, this will be treated as negative number. Add a test for "NaN" to fix this.
You repeat the document.getElementById... many times. Use a temporary variable to fix this.
In modern JavaScript, it is recommended to use let or const instead of var.
Be consistent in your use of semicolons at the end of lines.
Thus the code ends up as:
let countp = 0;
let countn = 0;
let isFinal = false;
function mapping() {
if (isFinal) {
return;
}
const num = parseInt(document.getElementById("num1").value);
let html = "";
if (Number.isNaN(num)) {
html = "invalid";
} else if (num === 0) {
html = "countp: " + countp + "<br>";
html += "countn: " + countn;
isFinal = true;
} else if (num > 0) {
html = "positive";
countp += 1;
} else {
html = "negative";
countn += 1;
}
document.getElementById("output").innerHTML = html;
}

Javascript Guessing Game - Counter Not Working

I am trying to create a Javascript guessing game where the user has 10 tries to guess a number between 1-999. I have to use a validate the number, use a loop and show alerts if the user gets a match and also when they run out of guesses. Using the number 45 just for testing. Each guess should be numbered and displayed using innerHTML. Problem is, the counter is stuck at zero. Not sure what I'm missing! Code below:
function myFunction() {
var userInput = document.getElementById("input").value;
var randomNum = 45;
// test for valid input number from 1 to 999
if (userInput < 0 || userInput > 999) {
alert("Your number must be from 1 to 999");
} else {
alert("Input OK");
}
var counter = 0;
while (counter < 10) {
counter++;
if (userInput == randomNum) {
alert("You win!");
}
if (userInput > randomNum) {
document.getElementById("loopResults").innerHTML += counter + "." + " Your answer: " + userInput + "." + " Guess lower! < br / > ";
alert("You have " + counter + " guesses left.");
} else if (userInput < randomNum) {
document.getElementById("loopResults").innerHTML += counter + "." + " Your answer: " + userInput + "." + "Guess higher! < br / > ";
alert("You have " + counter + " guesses left.");
}
break;
} // end while loop
} // end function myFunction()
This line
var counter = 0;
resets counter to 0 every time the function is called. One fix could be to set this as a global variable in this way
counter = 0; // note no var keyword
function myFunction() {...}
Then your calls to counter in the function will reference the global variable.
In addition, your while loop doesn't make sense. It should be a simple if statement to see if counter >= 10. Think about this logic after counter variable is being set correctly.
Step through the logic in your while loop.
The counter variable incrementing in each loop will already cause your loop to exit.
Setting a "break" at the end of the while loop means that you are guaranteed to exit after the first
Only break your loop when you actually want to exit it. In your case, that would probably be when the user has guessed the number or is out of tries.
The break command immediately ends the loop. Have a look at the MDN docs for more info!

JavaScript loops to store data in an array

I have a friend who has an assignment on arrays and because I lack experience in Javascript and she just needs some real quick help understanding how to implement a Javascript loop to store data in an array which converts a letter grade to a number. Can someone just guide her in a general direction?
https://docs.google.com/fileview?id=16uNNiooLalkm1QlszrqEPr2qqMGLjhrtQx7qCLw-7d2ftygre8GM6hyceJHj&hl=en\
Update: She states that she doesn't understand how to make it prompt again after the first time while storing data. Can someone just write a translation for a C++ code for do {}?
Here's a more or less complete solution - but it doesn't output the results to the HTML page but outputs it with the alert boxes.
var done = false,
classes = [],
total_credits = 0,
avg = 0;
while(!done){
var class_name = prompt("Enter class name"),
letter_grade = prompt("Enter letter grade for "+class_name),
credit_hours = prompt("Enter credit hours for "+class_name),
number_grade = {"A":4,"B":3,"C":2,"D":1,"F":0}[letter_grade];
if(class_name && letter_grade && credit_hours){
classes.push({
class_name: class_name,
letter_grade: letter_grade,
number_grade: number_grade,
credit_hours: credit_hours
});
total_credits += parseInt(credit_hours,10);
avg += number_grade*credit_hours;
}else
done = true;
}
avg = avg/total_credits;
for(var i=0; i<classes.length; i++){
alert(classes[i].class_name + " | " +
classes[i].letter_grade + " | " +
classes[i].credit_hours);
}
alert("Total credits: " + total_credits);
alert("GPA: " + avg.toFixed(2));
Basically, she should use a while loop.
in (mostly) pseudocode:
more_entries = true;
while(more_entries)
{
response = prompt("Question for the user","");
if (response == null)
{
more_entries = false;
}
else
{
// store value somewhere
}
}
Of course, this needs to be expanded to multiple prompts.

Categories

Resources