How to run a continuous loop in javascript - javascript

while(userInput!= -1)
{
var total=0.0;
var totalEarnings=0;
var item;
//var userInput;
var salesPerson=1;
var userInput= parseInt(prompt("outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
salesPerson++;
//alert("in while "+salesPerson);
//userInput= parseInt(prompt("Please enter noOfItemsSold of Item# "+item+" sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
//if(userInput!=-1)
//{
for(item=2;item<5;item++)
{
//userInput= parseInt(prompt("Please enter noOfItemsSold of Item# "+item+" sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
//var noOfItemsSold = parseInt( userInput);
if ( item == 1 )
{
total += userInput * 239.99;
}
else if (item == 2 )
{
total += userInput * 129.75;
}
else if ( item == 3 )
{
total += userInput * 99.95;
}
else if ( item == 4 )
{
total += userInput * 350.89;
}
var input= parseInt(prompt("Please enter noOfItemsSold of Item# "+item+" sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
}
totalEarnings = .09 * total + 200;
document.writeln( "<h1>SalesPerson#"+salesPerson+" Total Earnings this week is " +totalEarnings +"</h1>" );
}
I am trying to run the continuous loop. Script is calculating the total earnings of salesperson, and I want to run the script till the user enter -1.
I don't know what I am doing wrong but this is not working.
How can I fix this?

while (1) {
if (condition met) {
break;
}
}
your loop will always be true until your conditional test (insert yours is true) and then it will break and go on to the rest of your code.

Basically, the condition isn't evaluated until after the iteration of the loop has completed. So, if the user types in -1, the for loop will still be executed which is probably not what you want.
I suggest using the break; keyword to exit the loop. Trying something like this:
while(true) // Loop forever, since we'll break manually
{
var total = 0.0;
var totalEarnings = 0;
var item;
var salesPerson = 1;
var userInput = parseInt(prompt("outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #"+salesPerson+"\n"+" OR -1 to Exit "));
salesPerson++;
if(userInput == -1) // Exit immediately!
break;
for(item=2;item<5;item++)
{
// ...
}
}

I've cleaned up the code a bit:
var total;
var totalEarnings;
var item;
var salesPerson;
var userInput;
var input;
while ( userInput != -1 ) {
total = 0.0;
totalEarnings = 0;
salesPerson = 1;
userInput = parseInt( prompt( "outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #" + salesPerson + "\n OR -1 to Exit" ), 10 );
salesPerson++;
for ( item = 2; item < 5; item++ ) {
if ( item == 1 ) {
total += userInput * 239.99;
} else if (item == 2 ) {
total += userInput * 129.75;
} else if ( item == 3 ) {
total += userInput * 99.95;
} else if ( item == 4 ) {
total += userInput * 350.89;
}
input = parseInt( prompt( "Please enter noOfItemsSold of Item# " + item + " sold for SalesPerson #" + salesPerson + "\n OR -1 to Exit" ) );
}
totalEarnings = .09 * total + 200;
document.writeln( "<h1>SalesPerson#" + salesPerson + " Total Earnings this week is " + totalEarnings + "</h1>" );
}
Your loop will repeat as long as userInput has a value other than -1.
Now let's look at what each iteration of the loop does:
It assigns some initial values to a few variables.
It prompts the user to input a value; that value is assigned to userInput.
It then (rather bizarrely) repeats a similar prompt to the user, this time assigning them to input (not userInput) and using them to perform calculations for total.
The only time userInput is ever assigned a value is in step 2:
userInput = parseInt( prompt( "outsidePlease enter noOfItemsSold of Item# 1 sold for SalesPerson #" + salesPerson + "\n OR -1 to Exit" ), 10 );
And if you enter -1 as your input here, the loop will terminate, just as expected.

Related

Multiplying Combinations Array

So I need a tiny bit of help with this code, Some background information: The user inputs a number, the code takes the number and outputs various combinations of numbers that multiply to it.
For example:
Input: 7
Output: (1,7)(7,1).
*But what really happens:
*
Input: 7
Output: (7,1)
I want my code to reverse the numbers as well, so it makes can look like it has two combinations
var input= parseInt(prompt("Please enter a number larger than 1"));
var arr = [];
if(input <= 1) {
console.log("Goodbye!")
}
while(input > 0) {
var arr = [];
var input = parseInt(prompt("Please enter a number larger than 1"));
for (var i = 0; i < input; ++input) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
}
My code just need this tiny bit of problem fixed and the rest will be fine!
Your code has 2 infinite loop because you never change i and always increase input.
also in this line for (var i = 0; i < input; ++input) you never let i to be equal to the input so in your example (input=7) you can not have (7,1) as one of your answers. I think this is what you looking for:
var input = 1;
while(input > 0) {
input = parseInt(prompt("Please enter a number larger than 1"));
if(input > 1) {
var arr = [];
for (var i = 0; i <= input; ++i) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
continue;
}
else{
console.log("Goodbye!");
break;
}
}

Do While loop - Simply add numbers

I need to prompt the user to enter a series of numbers, or the word "quit".
Then, If the user enters a number, add the new number to a running total.
And, If the user enters the word "quit" the loop should stop execution.
I cant figure what should I do here. Im a beginner. i don't know how to make it work when user enter a word quit
let total = 0;
let number = 0;
do {
total += number;
number = parseInt(prompt('Enter a number: '));
if (number >= 0) {
document.writeln("<p>You entered " + number + "!</p>");
} else {
if (isNaN(number)) {
number = parseInt(prompt('Enter a number: '));
document.writeln("<p>Try again. We are looking for a number!</p>");
}
}
} while (number >= 0)
document.writeln("<p>The total is " + total + "</p>")
Use break to stop the javascript loop:
let total = 0;
let number = 0;
do {
total += number;
text = prompt('Enter a number: ');
if (text == "quit") {
break;
}
number = parseInt(text);
if (number >= 0) {
document.writeln("<p>You entered " + number + "!</p>");
} else {
if (isNaN(number)) {
number = parseInt(prompt('Enter a number: '));
document.writeln("<p>Try again. We are looking for a number!</p>");
}
}
} while(number >= 0)
document.writeln("<p>The total is " + total + "</p>")

Program won't return highest or smallest values using math methods

help im trying to get my code to alert The hisgest number input and lowest why isn't mine doing that?
let price;
let items = 0;
let sum=0;
let big = 0 ;
let small = 0;
price = Number(prompt("Please enter the price of the Item you choose to buy or enter -1 to stop: "));
while (price != -1){
sum=sum+price;
items++;
avg = sum/items;
Big = Math.max(Number(price));
small = Math.min(Number(price));
price = Number(prompt("Please enter the price of the Item you choose to buy or enter -1 to stop: "));
}
alert("You have purchased "+items+" items!");
alert("the sum of items you purchased is: $"+sum);
alert("the Averege of the items is: " + avg);
alert("The highest item price purchased was: "+ Big);
alert("The lowest item price was: "+ small);
Using function isNumeric to check for valid numbers.
Using array named itemsPurchasedto store all the valid purchases not including empty string, negative numbers.
Using template strings, destructuring assignment, Array.prototype.reduce() , Math.max(), spread operator , Math.min() and Array.prototype.length to get the desired result.
function isValidNumber(str) {
if (typeof str != "string") return false;
return (
!isNaN(str) &&
!isNaN(parseFloat(str))
);
}
function purchaseCalculation() {
let price,
expensive,
cheap,
itemsNumber,
average,
total,
itemsPurchased = [];
price = prompt(
"Please enter the price of the Item you choose to buy or enter -1 to stop: "
);
while (price !== "-1") {
if (isValidNumber(price) && Number(price) >= 0) {
itemsPurchased.push(Number(price));
}
price = prompt(
"Please enter the price of the Item you choose to buy or enter -1 to stop: "
);
}
expensive = itemsPurchased.length === 0 ? 0 : Math.max(...itemsPurchased);
cheap = itemsPurchased.length === 0 ? 0 : Math.min(...itemsPurchased);
total = itemsPurchased.reduce((total, item) => total + item, 0);
itemsNumber = itemsPurchased.length;
average = total === 0 ? 0 : total / itemsNumber;
return [cheap, expensive, total, itemsNumber, average];
}
const [cheap, expensive, total, itemsNumber, average] = purchaseCalculation();
alert(
`You have purchased ${itemsNumber} ${itemsNumber > 1 ? "items" : "item"}!`
);
alert(
`The sum of ${
itemsNumber > 1 ? "items" : "item"
} you purchased was: $${total}`
);
alert(
`The average of the ${itemsNumber > 1 ? "items" : "item"} was: ${average}`
);
alert(`The highest item price purchased was: ${expensive}`);
alert(`The lowest item price was: ${cheap}`);

Beginner - While Loop sum all user inputs under 50 - Javascript

I am still a beginner on Javascript and I have a question.
I would like to sum all user inputs under 50 if written 0 to stop the program and display their amount
By example:
First Number 5, Second number 3, Third Number 55, Fourth Number 0. (The program will print 8)
var userInput = parseInt(prompt('Write Number'));
while(userInput!=0) {
var userInput = parseInt(prompt('Try Again!'));
if(userInput < 50){
var sum = userInput + userInput;
}
document.write(sum + '<br>');
}
Thanks a lot
loop and add previous value if condition match :
var inputData = Number(prompt("Enter the input number"));
var finalOutput=0;
while (inputData > 0) {
if (!(inputData > 50)) {
finalOutput += inputData;
}
inputData = Number(prompt("Enter the input number"));
}
document.write("SUM is : " + finalOutput);
You'd do this:
var input = Number(prompt("Enter a number"));
var output = 0;
while (input > 0) {
if (!(input > 50)) {
output += input;
}
input = Number(prompt("Enter a number"));
}
document.write("The sum of all the numbers lower than 50 was " + output);

Entering 3 Numbers in Prompt and Getting the Max in JavaScript

I'm new to this. I'm working on exercises for a class and as the subject states I'm trying to have the user enter 3 numbers in the prompt window that appears. This works fine, but I'm trying to get the highest number that was entered to appear after the prompt is over. As I've noted in the code, can anything be added to Math.max to make this work, it's very close to working, but isn't quite there. I appreciate any help.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Number Input with Prompt
</title>
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber;
var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
highestNumber = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(value = parseInt( highestNumber ))){
highestNumber = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
total = total + value;
inputNumber = inputNumber + 1;
}
document.writeln(
"<h1>The highest number is " + finalMax + "</h1>" );
// -->
</script>
</head>
<body>
</body>
</html>
This approach compares the response to an up-to-date highest.
logic = "If value > highestNumber, highestNumber = value"
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber;
//var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(parseInt( value ))){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
if (highestNumber == undefined || highestNumber < value) {
highestNumber = value;
}
total = total + value;
inputNumber = inputNumber + 1;
}
document.writeln(
"<h1>The highest number is " + highestNumber + "</h1>" );
// -->
</script>
A better way to do that would be like this
var nums = new Array();
for(var i=0; i<3; i++){
nums[i] = window.prompt( "Enter number " + (i+1) + " of 3:" , "" );
}
document.writeln("<h1>The highest number is " + Math.max.apply(null, nums) + "</h1>" );
This approach logs all answers and runs the compare at the end, thus making use of Math.max()
logic = "highestNumber = Math.max(first,second,third)"
<script type = "text/javascript">
<!--
var total;
var inputNumber;
var value;
var highestNumber = [];
//var finalMax = Math.max. //<-----Can anything be added here to get the maximum number entered in the prompt window that appears?
total = 0;
inputNumber = 1;
while ( inputNumber <= 3 ){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
while(isNaN(parseInt( value ))){
value = window.prompt( "Enter number " + inputNumber + " of 3:" , "" );
}
highestNumber[inputNumber] = value;
total = total + value;
inputNumber = inputNumber + 1;
}
finalMax = Math.max(highestNumber[1], highestNumber[2], highestNumber[3]);
document.writeln(
"<h1>The highest number is " + finalMax + "</h1>" );
// -->
</script>
If you need or want to use Math.max to find your maximum, you should add each valid entry to an array of numbers and call Math.max.apply(null, numbers);
The following fiddle shows this in action: http://jsfiddle.net/T2Gxm/

Categories

Resources