Java Script Sum Numbers Application do while and for loop - javascript

I am having difficulty understanding a homework assignment. I would appreciate someone helping me with this matter. Please note I am not looking for someone to create the code for me, I am simply trying to understand why my code isn't working. This is the assignment:
Download the file below.
In the script element, add a do-while loop that prompts the user for an entry from 1 through 100. If the entry is invalid, display an
alert box with this message: “Please enter a number between 1 and
100”. Then, continue the loop until the entry is valid.
After the do-while loop, code a for loop that sums the numbers, and then display the second dialog box above. For instance, the sum for an
entry of four 1 + 2 + 3 + 4.
Add a do-while loop around all of the code that uses the third dialog box above to determine whether the first dialog box should be
displayed again so the user can enter another number. The application
should end for any entry other than “y”."
this is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sum of Numbers</title>
<script>
do
{
do
{
var theNumber = prompt("Enter first number", "10");
theNumber = parsInt(theNumber);
var numberOfLoops = (theNumber);
numberOfLoops = parsInt(numberOfLoops);
if(isNaN(theNumber) || theNumber <1 || theNumber > 100)
{
alert("Please enter a number between 1 and 100");
}
}
while (isNaN(theNumber) || theNumber <1 || theNumber > 100);
for (var counter = theNumber; counter>=1; counter--)
{
alert(counter);
}
sum == (theNumber + counter);
alert(sum);
again = prompt("Do it again? ('y' for yes)")
}
while(again = 'y');
</script>
</head>
<body>
<main>
<!-- Will show after JavaScript has run -->
<h1>Thanks for using the Sum of Numbers application!</h1>
</main>
</body>
</html>

Related

How would I take a variable like N and change it to a number that a user inputs?

I'm writing code that asks a user to input a number in a window prompt. When the prompt goes away, I want there to be a statement saying "Choose a number between 1 and n" with n being replaced by whatever number they input. Is that something I can do on the HTML side or is it done through JavaScript? I'm very new to this stuff. I've been searching this site all day and trying to figure this out from other posts but I haven't had any luck. Appreciate the help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<title>Higher Lower</title>
</head>
<body>
<div class="container">
<h1>Higher - Lower</h1>
<p>Guess a number between 1 and n.</p>
let valid_input = false;
let num_range, input;
let number_guesses = [];
// validating that max input is positive
while(!valid_input) {
input = window.prompt("Enter a positive, max value:");
num_range = Number(input);
if(num_range != NaN && num_range > 0) {
valid_input = true;
}
}
document.getElementById('button').addEventListener('choice', do_guess)
Give some id to <p> tag
for suppose - <p id="range">Guess a number between 1 and n.</p>
and add **document.getElementById("range").innerHTML = "Guess a number between 1 and " + input;** right next to **input = window.prompt("Enter a positive, max value:");**

How to setup a while loop with variables

I'm wanting to setup a while loop in heading 1 that allows a user to input three employees names with hours worked, hourly wage, and total pay. The loop needs to calculate those, account for overtime (over 40 hours receives 1.5x pay for any hours over 40), and display all three employees information after calculating.
What do I need to fix with my code to achieve the desired result?
I've referred to W3Schools and Youtube on "Creating a while loop" and "Declaring variables".
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="ISO-8859-1">
<title>JavaScript Page</title>
<script language="javascript">
"<h1> Martha's Diner</h1>"
// Variables get declared
var employeeCount; employeeCount = "3";
var hoursWorked; hoursWorked = " ";
var hourlyWage; hourlyWage = " ";
var notOvertime; notOvertime = "<=40";
var overTime; Overtime = ">40";
var totalPay; totalPay = "overTime + notOvertime";
var employeeName = " ";
var i = 0;
/// While Loop
while (i < employeeCount) {
employeeName = window.prompt ("Enter an Employee Name");
hoursWorked = window.prompt ("Enter Hours Worked");
hourlyWage = window.prompt ("Enter Hourly Wage");
if (hoursWorked <= 40)
hourlyWage * hoursWorked;
i++
}
</script>
</head>
<body>
</body>
</html>
I expected the loop to end and calculate keyed information, but the loop doesn't stop or calculate at all.
you are running an infinite while loop as any positive integer in java or javascript takes as true and check your closing loop braces.To input three values using while you can try like this:
var a=0;
while(a<3)
{
//your codes
//your codes
a=a+1;
}
this will execute 3 times

How to use a For Loop to make a triangle out output of the inputted numbers in JavaScript

Hello there!
I've been a given a Task like so:
Request the user to enter a number
Check if the user input is not empty. Also, check value entered is a number
Write on the HTML document a triangle out of the numbers as follow:
E.g. output: (let’s say the user entered number 10)
Your input number is 10.
10
11 11
12 12 12
13 13 13 13
14 14 14 14 14
15 15 15 15 15 15
The triangle should have 6 rows.
Use Comments explaining how the program works
Follow Indentation for clarity purposes.
Here is what I've tried so far:
var input = prompt("Enter a number: ");
if (input.value == '' || input.value == input.defaultValue) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
</body>
</html>
First of all, my IF statement is not working properly even if I input a string or don't leave a blank input field - the alert message still pop up;
And the result of document.writeln still printed even after alert pop's up with inputted string or empty field;
Please, someone, help me to solve this task or at least tell me what I'm doing wrong?
Thanks!
Look at the documentation for window.prompt().
Remove .value. input is the value.
Also, you aren't telling your code to not run if input is "bad".
// Be in a function so that you can return
(function() {
var input = prompt("Enter a number: ");
if (!input) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
// Get of of the function
return;
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
}());
|| input.value == input.defaultValue makes no sense since there is no such thing as input.defaultValue and, even if there was, you only need to check for an empty string. Also, input is already the response from the user so .value isn't needed.
You need to add an else condition to your if statement because even if no number is entered, your code will continue to do the looping.
Additionally, document.write() is only ever used in rare situations where you are building a new document from scratch, dynamically. It should not be used just to update an existing page's content. Instead, prepare an empty element ahead of time and when ready, update the content of that element.
Your loop configurations were a little off as well.
See other comments inline:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
var a = '';
// And then you need to go however many times the outer loop is on
for (var j = 1; j <= x; j++) {
a += input + ' '; // You just need to write out the current input value
}
input++; // Increase the value
// Update the output area on the page
output.innerHTML += a + "<br>";
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>
And, if and when you get more into String operations, you'll find that you don't even need the inner loop:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
// Set up the string to be written and then just repeat that
// however many times the outer loop is currently on.
output.innerHTML += (input + " ").repeat(x) + "<br>";
input++; // Increase the value
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>

Ping-Pong aka FizzBuzz test

I am new to programming and am currently stuck on the Ping-Pong aka FizzBuzz problem. (Make a webpage where the user is prompted to enter a number and every number up to that number is displayed. However, for multiples of three, the page prints "ping," for multiples of five, the page prints "pong," and for multiples of both three and five (15), the page prints "ping-pong.")
I've checked out other solutions on here (such as this one) and they've been helpful for understanding how to solve it. And I hope my javascript reflects that.
My problem is I'm stuck trying to take the input number from the form I have on the webpage and run it through the javascript, if that makes sense.
I'm pretty sure that part of my javascript is just a conglomeration of throwing everything I had at it, which is not the best. Could anyone check out my code and see what I'm doing wrong here?
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.2.js"></script>
<script src="js/scripts.js"></script>
<title>Ping-Pong Test</title>
</head>
<body>
<div class="container">
<h1>Ping Pong Test</h1>
<p>Let's play the Ping-Pong game. The Ping-Pong game is a simple test that involves loops, conditionals, and variables. Enter your number below to start</p>
<form id="start-form">
<label for="input-number">Your number:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Calculate</button>
</form>
<div id="end-number">
<ul id="results"></ul>
</div>
</div>
</body>
</html>
And my javascript:
$(document).ready(function () {
$("#start-form").submit(function(event) {
var a = document.getElementById("#input-number");
var num = a.elements[0].value;
var listItems = "";
var i;
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
console.log("Ping-Pong");
}
else if (i % 3 === 0) {
console.log("Ping");
}
else if (i % 5 === 0) {
console.log("Pong");
}
else{
console.log(i);
};
event.preventDefault();
};
});
Again, I'm new, so if anyone could break it down step by step, I'd really appreciate it. Thanks.
It is not right:
var a = document.getElementById("#input-number");
Must be one of the below lines:
var a = document.getElementById("input-number");
// Or
var a = $("#input-number").get(0);
// Or
var a = $("#input-number")[0];
But it will not solve your problem. Looking deep into your code. I guess you need to have a form an then get the first element:
var a = document.getElementById("start-form");
var num = a.elements[0].value;
But you can simplify even more. Why not just do it:
// remove the a variable
var num = $("#input-number").val(); // get the input-number value
Based on your code I think you just need some syntax cleaned up in order for jquery to use the value from your form.
I took your code, stripped it down for clarity and made a fiddle out of it.
Here is the link:
http://jsfiddle.net/zwa5s3ao/3/
$(document).ready(function(){
$("form").submit(function(event){
var num = $('#input-number').val()
for (var i = 1; i <= num; i++) {
if (i % 15 === 0) {
$('#list').append('<li>'+"Ping-Pong"+'</li>');}
else if (i % 3 === 0) {
$('#list').append('<li>'+"Ping"+'</li>');}
else if (i % 5 === 0) {
$('#list').append('<li>'+"Pong"+'</li>');}
else{
$('#list').append('<li>'+i+'</li>');}
};
event.preventDefault();
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Ping-Pong Test</title>
<body>
<form>
Your number:
<input type="number" name="input-number" id="input-number">
<input type="submit" value="Calculate">
</form>
<ul id="list"></ul>
</body>
Hope this helps!

combining javascript and html

Design and code a program which prompts a user for the year they were born, calculates the user's age and displays the user's age. If the user's age is over 40 then set the background color of the web page to red. The solution must use the JavaScript Date object and use programmer created functions for calculating the user's age.
pretty small problem i just need to make the screen turn red if age is more then 40 I just cant seem to make that happen...
<html>
<head>
<title> Age of person </title>
<div id="age"></div>
<body>
<script>
function determine_age_of_person ( year )
{
var today = new Date();
var now_year = today.getFullYear();
var age = now_year - year_person_was_born;
return age;
}
var year_person_was_born;
//unsure about below statement the '==' part
var age_of_person==age;
do
{
year_person_was_born = prompt("Enter year you were born", "");
year_person_was_born = parseInt (year_person_was_born1 );
}
while (is(year_person_was_born));
age_of_person = determine_age_of_person ( year_person_was_born );
if (age_of_person>40)
document.body.style.backgroundColor = "red";
else
document.body.style.backgroundColor = "white";
document.getElementById("age").innerHTML = "You are " + age_of_person + " years old";
</script>
</body>
</html>
Ok there are lot of code placement issues here (you have an html element outside of the body element, return statements outside of functions, function arguments that you don't use). Here is a simplified version of what you are building (demo)
<html>
<head>
<title> Age of person </title>
</head>
<body>
<div id="age"></div>
<script>
function determine_age_of_person (year) {
return (new Date()).getFullYear() - year;
}
var age_of_person = determine_age_of_person(parseInt (prompt("Enter year you were born", ""), 10));
if (age_of_person>40) {
document.body.style.backgroundColor = "red";
} else {
document.body.style.backgroundColor = "white";
}
document.getElementById("age").innerHTML = "You are " + age_of_person + " years old";
</script>
</body>
</html>
Here is breakdown of the changes I made:
Moved <div id="age"></div> inside the body
Used argument year in determine_age_of_person() instead of global variable
Combined prompt, parseInt and determine_age_of_person into one line (and added a radix to parseInt, because JavaScript has weird rules related to non base 10 numbers, it's a good habit to get into)
Added curly braces to if statement
Removed useless code like do() and while()
change
if (year_person_was_born > 40)
to
if (age_of_person > 40)

Categories

Resources