how to add if..else statement in my code - javascript

In my code, how can I add the if statement so it print different statements depend on different situtation. for example, I like to have a statement for the sum < 1, and else sum > 1. I try w3 school but the example if statement does not work for some reason
<!DOCTYPE html>
<!-- Network Latency Calculator -->
<html>
<head>
<meta charset = "utf-8">
<title>Network Latency Calculation</title>
<script>
var firstNumber; // first string entered by user
var secondNumber; // second string entered by user
var thirdNumber; // third string entered by user
var fourthNumber; // fourth string entered by user
var number1; // first number to add
var number2; // second number to add
var number3; // third number to add
var number4; // fourth number to add
var sum; // sum of number1 and number2 and number3 and number4
// read in first number from user as a string
firstNumber = window.prompt( "Enter the Propagation time (in milliseconds)" );
// read in second number from user as a string
secondNumber = window.prompt( "Enter the Transmission time (in milliseconds)" );
// read in third number from user as a string
thirdNumber = window.prompt( "Enter the Queuing time (in milliseconds)" );
// read in fourth number from user as a string
fourthNumber = window.prompt( "Enter the Propagation delay (in milliseconds)" );
// convert numbers from strings to integers
number1 = parseInt( firstNumber );
number2 = parseInt( secondNumber );
number3 = parseInt( thirdNumber );
number4 = parseInt( fourthNumber );
sum = number1 + number2 + number3 + number4; // add the numbers
// display the results
document.writeln( "<h1>The network latency is " + sum + "</h1>" );
</script>

First of all you might want to look here:
https://www.w3schools.com/jsref/met_doc_writeln.asp
Right now you writing in the head of the html not in the body
<body>
<p>Note that write() does NOT add a new line after each statement:</p>
<pre>
<script>
var NowDate = new Date();
var number1 = NowDate.getHours(); //added current hour 0-23
var number2 = 5; // second number to add
var number3 = 0.3; // third number to add
var sum = number1+number2*number3;
if (sum > 5){
document.write("That's a");
document.write(" big Sum ("+sum+")");
} else if (sum === 4) {
document.write("Sum =");
document.write(" 4");
}else{
document.write("Sum is ");
document.write("small ("+sum+")");
}
</script>
</pre>
<p>Note that writeln() add a new line after each statement:</p>
<pre>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice day!");
</script>
</pre>
</body>

First off, judging by your short description on what you want, I understand you want the statement of whatever you want to say after you calculate the total. To do that, it is really easy.
Example:
sum = number1 + number2 + number3 + number4; // add the numbers
if(sum > 1){
//Your code
} else {
//Your code
}
The reason I didn't put else if because if the sum is greater than one, it runs whatever statement you want it to run. If it isn't, then it will run the other, the else statement.
If you want to look at more if/else examples, you can go on this StackOverflow post and check the examples they have and how to use it.

After you get the sum, you could add an if-statement similar to this code if you so desire:
if (sum < 1) {
document.write ("The sum is less than one");
} else if (sum > 1) {
document.write( "The sum is more than one");
}
If you have more questions about if-conditional statements O'Reilly has a number of excellent technical books dealing with JavaScript.
var firstNumber; // first string entered by user
var secondNumber; // second string entered by user
var thirdNumber; // third string entered by user
var fourthNumber; // fourth string entered by user
var number1; // first number to add
var number2; // second number to add
var number3; // third number to add
var number4; // fourth number to add
var sum; // sum of number1 and number2 and number3 and number4
// read in first number from user as a string
firstNumber = window.prompt( "Enter the Propagation time (in milliseconds)" );
// read in second number from user as a string
secondNumber = window.prompt( "Enter the Transmission time (in milliseconds)" );
// read in third number from user as a string
thirdNumber = window.prompt( "Enter the Queuing time (in milliseconds)" );
// read in fourth number from user as a string
fourthNumber = window.prompt( "Enter the Propagation delay (in milliseconds)" );
// convert numbers from strings to integers
number1 = parseInt( firstNumber );
number2 = parseInt( secondNumber );
number3 = parseInt( thirdNumber );
number4 = parseInt( fourthNumber );
sum = number1 + number2 + number3 + number4; // add the numbers
if (sum < 1) {
document.write ("The sum is less than one");
} else if (sum > 1) {
document.write( "The sum is more than one");
}
// display the results
document.writeln( "<h1>The network latency is " + sum + "</h1>" );

Related

Page displays formula rather than result (but for only ONE of the cases)

I'm a student currently learning JavaScript. As practice, I wanted to make a cute reading randomizer for a friend with a simple form and a if else input validation process.
Both of my first two cases function as I expect them two, but the third, the one that actually does the calculation, does not send the result of the calculation to be displayed, but rather the formula. I'm not sure where I went wrong.
function pickfic() {
// Get the value of the input fields
let minNumChosen = document.getElementById('minNum').value;
let maxNumChosen = document.getElementById('maxNum').value;
// If input Not a Number or min bigger than max
let reply;
if (isNaN(minNumChosen) || isNaN(maxNumChosen) || minNumChosen > maxNumChosen ) {
reply = "I think you pissed off my sandwich. Also, those numbers make no sense to me.";
}
// If min is zero
else if (minNumChosen == 0) {
reply = "Really, dude? You have an Excel line for 'zero'?? Witch.";
}
else {
// if range is correct, randomize number
const generateRandomNumber = (minNumChosen, maxNumChosen) => {
return Math.floor(Math.random() * (max - min) + min);
};
reply = "Today, you should read fic number " + generateRandomNumber + "!";
}
document.getElementById("result").innerHTML = reply;
}
For the last case, the page displays : "Today, you should read fic number (minNumChosen, maxNumChosen) => { return Math.floor(Math.random() * (max - min) + min); }!"
You can find the codepen here.
EDIT: Turns out I found another bug, which is probably logic based. It seems that for my function, 2 is greater than 10. So it must be judging by the first digit...
function pickfic() {
// Get the value of the input fields
let minNumChosen = document.getElementById('minNum').value;
let maxNumChosen = document.getElementById('maxNum').value;
// If input Not a Number or min bigger than max
let reply;
if (isNaN(minNumChosen) || isNaN(maxNumChosen) || minNumChosen > maxNumChosen ) {
reply = "I think you pissed off my sandwich. Also, those numbers make no sense to me.";
}
// If min is zero
else if (minNumChosen == 0) {
reply = "Really, dude? You have an Excel line for 'zero'?? Witch.";
}
else {
// if range is correct, randomize number
const generateRandomNumber = (min, max) => {
return Math.floor(Math.random() * (max - min) + min);
};
reply = "Today, you should read fic number " + generateRandomNumber(parseInt(minNumChosen), parseInt(maxNumChosen)) + "!";
}
document.getElementById("result").innerHTML = reply;
}
<input id="minNum" placeholder="min">
<input id="maxNum" placeholder="max">
<div id="result"></div>
<button onclick=pickfic()>Click</button>
You had to add parenthesis to generateRandomNumber()
And also make the minNumChosen and maxNumChosen into integers with parseInt().
There was also another mistake where you didn't name the parameters of your generateRandomNumber function (min, max).
function pickfic() {
// Get the value of the input fields
let minNumChosen = document.getElementById('minNum').value;
let maxNumChosen = document.getElementById('maxNum').value;
// If input Not a Number or min bigger than max
let reply;
if (isNaN(minNumChosen) || isNaN(maxNumChosen) || minNumChosen > maxNumChosen ) {
reply = "I think you pissed off my sandwich. Also, those numbers make no sense to me.";
}
// If min is zero
else if (minNumChosen == 0) {
reply = "Really, dude? You have an Excel line for 'zero'?? Witch.";
}
else {
// if range is correct, randomize number
const generateRandomNumber = Math.floor(Math.random() * (maxNumChosen - minNumChosen) + minNumChosen);
reply = "Today, you should read fic number " + generateRandomNumber + "!";
}
document.getElementById("result").innerHTML = reply;
OR
You created a function which takes in values but you didn't provide the min and max value while calling the generateRandomNumber function
function pickfic() {
// Get the value of the input fields
let minNumChosen = document.getElementById('minNum').value;
let maxNumChosen = document.getElementById('maxNum').value;
// If input Not a Number or min bigger than max
let reply;
if (isNaN(minNumChosen) || isNaN(maxNumChosen) || minNumChosen > maxNumChosen ) {
reply = "I think you pissed off my sandwich. Also, those numbers make no sense to me.";
}
// If min is zero
else if (minNumChosen == 0) {
reply = "Really, dude? You have an Excel line for 'zero'?? Witch.";
}
else {
// if range is correct, randomize number
const generateRandomNumber = (min,max) => {
return Math.floor(Math.random() * (max - min) + min);
};
reply = "Today, you should read fic number " + generateRandomNumber(minNumChosen, maxNumChosen) + "!";
}
document.getElementById("result").innerHTML = reply;
}
I figured out the last bug thanks to #SchokokuchenBäcker's input on the first issue.
My conditional was comparing strings, which is why 20 was smaller than 5 !
Writing the first conditional like this:
if (isNaN(minNumChosen) || isNaN(maxNumChosen) || parseInt(minNumChosen) >= parseInt(maxNumChosen) )
makes it functional!

What is the statement i need next to determine my output given a total?

I'm quite new to JavaScript so apologies in advanced, but I'm wanting too learn!
In my html form I am asking the customer for 3 numbers (number 1,2,3) and then in my JavaScript I am calculating the total of all of them. I need to work out my next bit of code so I can:
Given the total of the numbers give I can print out to the customer you're item is free (less than 180) or it has a cost (more than 180)
Given the number is under or over a certain amount return an error message
Where would be the best place to go with this ?
function Calculate() {
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var number3 = document.getElementById("number3").value;
// var totalOfNumbers = Number(number1) + Number(number2) + Number(number3);
document.getElementById("total").innerHTML = Number(number1) + Number(number2) + Number(number3);
}
You need to use an if construct.
The code would be :-
function Calculate() {
var number1 = document.getElementById("number1").value;
var number2 = document.getElementById("number2").value;
var number3 = document.getElementById("number3").value;
// use parseInt instead of Number()
var totalOfNumbers =
parseInt(number1) + parseInt(number2) + parseInt(number3);
// string message to be displayed
var message = "";
// enter you own values
var minAmount = 0;
var maxAmount = 1000;
// checking if total of the numbers is under or over a certain amount;
// if it is, then showing an error message.
if (totalOfNumbers < minAmount || totalOfNumbers > maxAmount) {
message = "Error! Please enter valid amounts."
}
// Checking if total of the numbers is under 180;
// if it is, then displaying the item is free.
else if (totalOfNumbers < 180) {
message = "You're item is free!";
}
// Checking if total of the numbers is greater than or equal to 180;
// if it is, then displaying the item is not free, and its cost.
else {
message = "You're item is not free. It has a cost of $" + totalOfNumbers;
}
document.getElementById("total").innerHTML = message;
}

Application that calculates price depending on quantity in JavaScript

I have this exercise that I am struggling to comprehend the logic to achieve the outcome when qty is more than 3:
An application to calculate the price of pizzas (listed below) that will be purchased during a promotional period. The number of pizzas will be entered by the user.
One large pizza will cost $6.45.
Two large pizzas will cost $12.00.
Three large pizzas will cost $14.00.
Four or more pizzas will use a combination of the above prices to ensure the best price for the customer. For example, the best price for five pizzas would be two pizzas ($12.00) + three pizzas ($14.00).
The algorithm must also take account of all possible situations by using sequence, selection and iteration structures.
Below is my code so far:
let calcOrder = () => {
// get inputs
var qty = document.getElementById("quantity").value;
var price = 6.45;
var price2 = 12.0;
var price3 = 14.0;
var totalPrice;
// validate missing, non-digit, negative inputs
if (qty == "") {
document.getElementById("message").innerHTML = "Missing input";
} else if (isNaN(qty)) {
document.getElementById("message").innerHTML = "Numbers only";
} else if (qty < 0) {
document.getElementById("message").innerHTML =
"Negative numbers are not allowed";
} else {
//calc total
if (qty == 1)
{
totalPrice = price;
}
else if (qty == 2)
{
totalPrice = price2;
}
else if (qty == 3)
{
totalPrice = price3;
}
//output total
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
}
// prevent form from submission
return false;
};
Thank you
you can use division and mod operation to calculate the price:
(this example assuming all check you did valid input are already done)
const qte = document.getElementById("quantity").value;
const price = 6.45;
const price2 = 12.0;
const price3 = 14.0;
let totalPrice;
const total3 = parseInt("" + qte / 3 + "", 10) * price3;
const total2 = parseInt("" + (qte % 3) / 2 + "", 10) * price2;
const total1 = parseInt("" + ((qte % 3) % 2) + "", 10) * price;
totalPrice = total1 + total2 + total3;
document.getElementById("message").innerHTML =
`Total price is $${totalPrice}`;
what is actually happening in the code
well it is basic mathematics, if you want to know how many 3s in your number you divide by 3 and take the integer part or floor of the result, basic division. for example 10 = 3*3 + 1 so you have 3 as a result of that division.
since you only want to apply the price of 3 pizza as top priority you do this division then multiply by the price for 3.
then come the priority for the price of 2 pizzas, but you not interested for the total number of pizzas, only what was left after you payed with the price of 3 pizzas so you do the mod operator (%) with 3 to get was left unpaid, for example 8 = 3*2 + 2, this give us 2 pizzas left unpaid so you apply the price of 2 pizzas.
the you check if a single pizza is left after you paid for 2 pizzas (which would only happen if only a single pizza was left after you paid for 3). if there is single pizza you pay for it otherwise you add nothing.
ps: after paying for pizzas in multiple of three, you only add the price of 2 pizzas or a single one, but never both, otherwise price of 3 pizzas would apply instead.
hope the explanation is clear, if not leave a comment and i'll try to adjust what was not clear.

How to store results of an iteration in a variable

For educational reasons, I am working through a simple algorithm that randomly generates two numbers and then asks for the addition of generated numbers, tells you if you are right or wrong on response, and tracks results out of 100. I would like to include function that reports something like the following: "You have gotten 80/100 correct" But am held up with syntax, I think. I can't get my score variable to count up with correct answers.
Here is my code as it stands..
do{
var firstnum = Math.floor(Math.random()*10);
var secondnum = Math.floor(Math.random()*10);
var result = firstnum+secondnum;
var score=0;
var answer = prompt("what is "+firstnum + "+" + secondnum);
if(answer < result || answer > result){alert("Wrong! " + "The correct answer
is " + result)};
if(answer == result){alert("you are correct!"), score++};
alert("Awesome, You have gotten " + score + " correct so far!!!");}
while(score<100);
Just get me over the hump. I am hopeful that I can really get my head wrapped around more concepts if I can get through this little guy.
You reset score in every loop to zero. Move the declaration and initialization to top.
Some hints:
no need for semicolons after a block statement { /* code */ },
convertion of strinn to number with unary plus +
use a single if statement with else block for the opposite of the check.
// declare all variables at top
var firstnum,
secondnum,
result,
score = 0,
answer;
do {
firstnum = Math.floor(Math.random() * 10);
secondnum = Math.floor(Math.random() * 10);
result = firstnum + secondnum;
// covert input string to number with unary plus
answer = +prompt("what is " + firstnum + "+" + secondnum);
// ^
// just check the result and omit a second if clause,
// because it is just the opposite check
// take the more easy/shorter check first
if (answer === result ) {
alert("you are correct!");
score++;
} else {
alert("Wrong! " + "The correct answer is " + result)
}
alert("Awesome, You have gotten " + score + " correct so far!!!");
} while (score < 2) // take a small number for scoring check

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.

Categories

Resources