While Loop in JavaScript, stuck in infinite loop [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Here is my code. I am currently stuck in an infinite loop. The program must ask the number of bottles collected for each day for 7 times. So the loop should iterate 7 times. I then must display the total bottles and the total payout of each bottles (which is multiplied but .10) at the end.
function main() {
alert("Welcome to the program");
var totalBottles = 0;
var todayBottles = 0;
var totalPayout = 0;
var keepGoing = "y";
var counter = 1;
while (keepGoing == "y")
getBottles(totalBottles, todayBottles, counter);
calcPayout(totalPayout, totalBottles);
printInfo(totalBottles, totalPayout);
keepGoing = prompt("Do you want to keep going? Enter y for yes");
}
function getBottles(totalBottles, todayBottles, counter) {
while (counter < 7) {
todayBottles = prompt("Enter the number of bottles returned for the day");
totalBottles = (totalBottles + todayBottles);
counter = (counter + 1);
}
}
function calcPayout(totalPayout, totalBottles) {
totalPayout = 0;
totalPayout = (totalBottles * 0.10);
}
function printInfo(totalBottles, totalPayout) {
alert("The total number of bottles returned is", totalBottles);
alert("The total paid out is", totalPayout);
}
//calls main
main();
alert("End of program");

// please try to understand what it's doing and why was your code not printing the correct info.
function main() {
alert("Welcome to the program");
var totalBottles = 0;
var todayBottles = 0;
var totalPayout = 0;
var keepGoing = "y";
var counter = 1;
while (keepGoing == "y") {
totalBottles = getBottles(totalBottles, todayBottles, counter);
totalPayout = calcPayout(totalPayout, totalBottles);
printInfo(totalBottles, totalPayout);
keepGoing = prompt("Do you want to keep going? Enter y for yes");
}
}
function getBottles(totalBottles, todayBottles, counter) {
while (counter < 7) {
todayBottles = prompt("Enter the number of bottles returned for the day");
//alert(todayBottles);
totalBottles += parseInt(todayBottles);
//alert(totalBottles);
counter = (counter + 1);
}
return totalBottles;
}
function calcPayout(totalPayout, totalBottles) {
totalPayout = 0;
totalPayout = (totalBottles * 0.10);
return totalPayout;
}
function printInfo(totalBottles, totalPayout) {
alert("The total number of bottles returned is " + totalBottles);
alert("The total paid out is " + totalPayout);
}
//calls main
main();
alert("End of program");

just put { after
while (keepGoing == "y")
because according to your code your while loop body contains only one line
getBottles(totalBottles,todayBottles,counter);
so your program is stuck on that line as keepGoing is always True

Related

JavaScript code doesn't work, no errors or stops [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
I am new to JavaScript and I try to write a decoder to caesar cipher. But my code doesn't work, and there is no errors shown and it doesn't stop.
let word = "привет";
let shift = 3;
let result = "";
for (let i = 0; i < word.legth; i++){
if ('А'.charCodeAt(0) <= word[i].charCodeAt(0) <= 'Я'.charCodeAt(0)) {
let char = ((word[i].charCodeAt(0) + shift - 'А'.charCodeAt(0)) % 32) + 'А'.charCodeAt(0)
result = result + String.fromCharCode(char);
}
else if ('а'.charCodeAt(0) <= word[i].charCodeAt(0) <= 'я'.charCodeAt(0)) {
let char = ((word[i].charCodeAt(0) + shift - 'а'.charCodeAt(0)) % 32) + 'а'.charCodeAt(0)
result = result + String.fromCharCode(char);
}
else {
result = result + word[i];
}
}
console.log(result)
Change word.legth to word.length
let word = 'привет';
let shift = 3;
let result = '';
for (let i = 0; i < word.length; i++) {
if ('А'.charCodeAt(0) <= word[i].charCodeAt(0) <= 'Я'.charCodeAt(0)) {
let char =
((word[i].charCodeAt(0) + shift - 'А'.charCodeAt(0)) % 32) +
'А'.charCodeAt(0);
result = result + String.fromCharCode(char);
} else if (
'а'.charCodeAt(0) <=
word[i].charCodeAt(0) <=
'я'.charCodeAt(0)
) {
let char =
((word[i].charCodeAt(0) + shift - 'а'.charCodeAt(0)) % 32) +
'а'.charCodeAt(0);
result = result + String.fromCharCode(char);
} else {
result = result + word[i];
}
}
console.log(result);

How to loop randomize javascript function in html [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I know this is very simple question, but I don't know why it only giving same output.
I'm trying to randomize 4 numbers from 1 to 100
I'm very new to javascript
this is my code:
function myFunction() {
var text = "",
i;
var x = Math.floor((Math.random() * 100) + 1);
for (i = 1; i <= 4; i++) {
text += " number " + x;
}
document.getElementById("rand").innerHTML = text;
}
<button onclick="myFunction()">Generate</button>
<p id="rand"></p>
You are calling your randomize part of code outside the for loop. It should be recalculated on every step of the loop. Something like this
function myFunction() {
var text = "",
i;
for (i = 1; i <= 4; i++) {
var x = Math.floor((Math.random() * 100) + 1);
text += " number " + x;
}
document.getElementById("rand").innerHTML = text;
}
<button onclick="myFunction()">Generate</button>
<p id="rand"></p>
function myFunction() {
var text = "";
var i = 0;
randNos = [];
while(i<4) {
x = rand();
if(randNos.indexOf(x) === -1) {
text += " number " + x ;
randNos.push(x);
i++
}
}
document.getElementById("rand").innerHTML = text;
}
function rand() {
return Math.floor((Math.random() * 100) + 1);
}
You were trying to print the same random no 4 times. You just need to move your random no line inside the loop

Javascript word counter [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I wanted to make a basic word counter based on the amount of whitespaces in a sentence, but for some reason it doesn't work.
function countWords(str) {
if (typeof str == "string" && str.length > 0) {
var counter = 1;
for (var i; i < str.length; i++) {
if (str[i] === " ") {
counter += 1;
}
}
return counter;
} else {
throw Error("You must input a string.");
}
}
console.log(countWords("hello World"));
This throws 1 instead of 2.
You shouldn't use a loop for this. You would rather just split the string by space and take the resulting array's length
let countWords = str => str.split(' ').length;
console.log(countWords("foo bar"));
Initialize i to zero.
Replace for (var i; with for (var i=0;
You must initilize the counter inside the for, like var i = 0; here is your code
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
countWords("hello World");
Or you can count words with str.split(" ").length
Your for loop was wrong
function countWords(str) {
if (typeof str=="string" && str.length>0) {
var counter=1;
for (var i = 0;i<str.length;i++) {
if (str[i]===" ") {
counter+=1;
}
}
return counter;
}
else {
throw Error("You must input a string.");
}
}
var str = "hello World this is me";
console.log(countWords(str));

Javascript Smallest Multiple Keeps Crashing

I am currently going through project euler trying to get better at javascript. I am stuck on one problem that i can't seem to figure out.
The question is:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
So I searched stack and found a few similar topics when i got stuck but everyones code seems to be a bit more complex than what I came up with. My problem is i was able to create the correct program to find the smallest multiple from 1-10 which i was able to get 2520 with.
However, when i adjust my program to work for numbers 1-20 it crashes. I can get 1-19 but once i do 20 i keep crashing. Here is my code. If you change it to count != 10 and i <= 10 you can get the answer 2520 but 20 just doesn't seem to work. Any help would be appreciated.
<script>
var num = 0;
var count = 0;
while (count != 20) {
num++;
count = 0;
for (var i = 1; i <= 20; i++) {
if (num % i == 0) {
count++;
}
}
}
console.log(num);
console.log(count);
</script>
It doesn't crash, just takes long time, since your script is inefficient.
<script>
var num = 0;
var count = 0;
var numbers=20;
while (count != numbers) {
num+=numbers;
count = 0;
for (var i = 1; i <= numbers; i++) {
if (num % i == 0) {
count++;
}
else {break;}
}
}
console.log(num);
console.log(count);
</script>
Yeah, not breaking, just taking a REALLY long time. This should be a much more efficient approach:
var num = 1;
var isDivisible = false;
var startTime = (new Date().getTime());
while (!isDivisible) {
for (var i = 20; i > 1; i--) {
if (num % i !== 0) {
isDivisible = false;
num = num + (i + 1);
break;
}
else {
isDivisible = true;
}
}
}
console.log(num);
console.log("Finished in " + (((new Date().getTime()) - startTime) / 1000) + " seconds");
Results:
232792560
Finished in 0.166 seconds
Note: above results from JSFiddle . . . finished in 26.57 seconds in Firebug. :)

How to add a variable in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
var count=0 ;
for(var x=0; x<data_len; x++)
{
count = count + num_arr[x];
}
// alert(count);
If count = 352 I want to add 3+5+2 which is 10 and then 1+0 which is 1.
function sumParts(x) {
var sumX = 0;
var strX = x.toString();
var arrX = strX.split("");
for (a = 0; a < arrX.length; a++) {
sumX += parseInt(arrX[a], 10);
};
return sumX;
}
y = sumParts(count);
z = sumParts(y);
// y = 10; (3 + 5 + 2)
// z = 1; (1 + 0)
And, I believe (untested), if the return was changed to return sumParts(sumX), it would continue until it was a single digit integer.
You have an array of strings, not numbers. You can convert them to numbers with:
count = count + +num_arr[x];
The second + is the unary plus operator, and will cast num_arr[x] to a number.
If your numbers are all integers, you can use:
count = count + parseInt(num_arr[x], 10);
or (if you have floats):
count = count + parseFloat(num_arr[x]);
Convert count into a string :
var count = 352;
count += ''; // makes a string : "352"
while (count.length > 1) {
count = Function('return ' + count.split('').join('+') + ';')() + '';
}
This part :
Function('return ' + count.split('').join('+') + ';')
Gives successively :
function () { return 3+5+2; }
function () { return 1+0; }

Categories