JavaScript Word Generator - javascript

I'm making a word generator. You enter in ten strings of your choice. It should output one string that it randomly selected. It outputs a randomly selected number instead and it shouldn't. It should output a string entered by the user. I don't get errors.
How do I get this to display the user input?
Any suggestions? I've been stuck on this the last few days.
function randomWordGenerator() {
// Define the variables
var userInput = [];
var answer = [], range = 1;
var array = [];
var set = [];
// Prompt for String
for(var index = 0; index < 10; index++) {
userInput = prompt("Please enter string." + (index + 1));
document.write("You entered: " + userInput + "\n");
}
// Generator
for(var i = 0; i < range; i++) {
answer[i] = Math.floor((Math.random() * 10) + 1);
}
// Generator Pick Display
document.write("The generator choose: " + answer);
}
randomWordGenerator();

You have to save the user input into the array. What you are doing in your code is overwriting userInput all the time, i.e. only the last word the user entered is save in that variable. And then you generate some random numbers, push them all into an array and output that to the user. Here is how it would work:
function randomWordGenerator() {
// Define the variables
var array = [];
// Prompt for String
for (var index = 0; index < 10; index++) {
var userInput = prompt("Please enter string." + (index + 1));
array.push(userInput);
document.write("You entered: " + userInput + "\n");
}
// select random number from array in which you stored the words
var answer = array[Math.floor(Math.random() * array.length)];
// Generator Pick Display
document.write("The generator choose: " + answer);
}
randomWordGenerator();

Related

Button wont call a function in JavaScript?

completely new to javascript as of an hour ago. Trying to get a button to call a function. It was working fine like 20 minutes ago, but all of a sudden it's being touchy and deciding now to work, what am I missing here?
function sortFunction() {
var totalNums = prompt("How many numbers would you like to enter?", "");
var numsArray = [];
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1), "");
numsArray[i] = nums;
document.write(numsArray[i] + " ");
}
if (nums == "x") break; // if user enters x, break loop
}
<p> Click the button to enter and display an array of numbers!</p>
<button onclick="sortFunction()">Click Me</button>
As previously commented, the if statement needs to be just after var nums = prompt line. We also use return most often to exit out of functions.
More importantly, rather than limiting the incorrect option to 'x', why not adjust it to:
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1), "");
if (typeof nums === "number") {
numsArray[i] = nums;
document.write(numsArray[i] + " ");
} else {
return;
}
}
all you have to do is put "if" inside of the function
function sortFunction() {
var totalNums = prompt("How many numbers would you like to enter?", "");
var numsArray = [];
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1), "");
numsArray[i] = nums;
document.write(numsArray[i] + " ");
if (nums == "x") break; // if user enters x, break loop
}
}
<p> Click the button to enter and display an array of numbers!</p>
<button onclick="sortFunction()">Click Me</button>
The problem here is with if condition it was placed outside the for loop.
So this might work for you putting condition inside and will break the loop on value x
function sortFunction() {
var totalNums = prompt("How many numbers would you like to enter?", "");
var numsArray = [];
for (i = 0; i < totalNums; ++i) {
var nums = prompt("Please enter number " + (i + 1),
if (nums == "x"){
break;
}
else{
numsArray[i] = nums;
document.write(numsArray[i] + " ");
}
}
}

Make an array in java script with window.prompt()

I try to make an Array in javascript with number of elements and elements inputted by user through window.prompt().
This is what i got by now :
var n = window.prompt("Insert number of numbers", "")
var nr = new Array(n)
for (i = 0; i < n; i++) {
nr[i] = window.prompt("Number: ", "")
}
for (i = 0; i < n; i++) {
if ((i + 1) % 2 != 0) {
if (nr[i] % 2 == 0)
document.write("Even numbers on odd position are: ", nr[i], "<br/>")
}
}
document.write("The numbers are :")
for (i = 0; i < n; i++) {
document.write(nr[i] + "<br/>")
}
On web page shows nothing.
Defining elements.
The first thing in your code is that you should define an array as this:
var numbers = [];
In this array, you will handle every element you will receive from the prompt. So, with this said, you just need the total amount of numbers that you will use which can be retrieved by doing a prompt for a number:
var times = window.prompt("Insert number of numbers: ");
So, times would be our variable containing the amount of numbers we should ask the user, which will be saved on numbers.
Asking user for numbers X amount of times.
Now, what you could do is just a simple for loop which only job is to push the new number provided by the user:
for (let i = 0; i < times; i++) {
numbers.push(window.prompt(`Number ${i+1}: `))
}
This will give the user a prompt saying Number X:, which means the number that is being added.
Checking numbers for even and odds.
And for your functionality of giving a message when there is an even number in an odd index, you could do this:
numbers.forEach((n,i)=>{
if(n%2===0 && i%2!=0){
document.write(`Even number ${n} in odd position ${i} <br/>`);
}
});
Which will check every number you received from the user and check in one inline condition if even number is in odd position and will output the line only if this condition is true.
Printing the numbers.
And simply to output every number you can do:
numbers.forEach((n)=>{
document.write(n + "<br/>")
});
See how it works:
var times = window.prompt("Insert number of numbers"), numbers = [];
for (let i = 0; i < times; i++) {
numbers.push(window.prompt(`Number ${i+1}: `))
}
numbers.forEach((n,i)=>{
if(n%2===0 && i%2!=0){
document.write(`Even number ${n} in odd position ${i} <br/>`);
}
});
document.write("The numbers are: <br/>")
numbers.forEach((n)=>{
document.write(n + "<br/>")
});

How to get the mean(average) for elements of user input array?

This may be a dumb question, but I'm very new to JavaScript and can't for the life of me figure out how to get the mean(average) of user inputted array elements. Here's the code I wrote so far where the user is prompted to enter the number of elements in the array and loops back and prompts that many times to enter the elements. Any help is appreciated. Thanks.
<html>
<head>
<title>Title</title>
<script type="text/javascript">
var nums = new Array();
var N = prompt("How many numbers would you like to enter? ");
N = parseInt(N);
var i = 0;
for(i = 0; i <= N - 1; i++)
{
nums[i] = prompt("Enter your numbers: ");
document.write("Number you chose: " + nums[i] + "<br />");
}
</script>
</head>
<body>
</body>
</html>
You have to use a summation var s to add value of inputs and calculate the average at end using this formula average = s / N:
<script type="text/javascript">
var nums = new Array();
var N = prompt("How many numbers would you like to enter? ");
N = parseInt(N);
var i = 0, s = 0;
for(i = 0; i <= N - 1; i++)
{
nums[i] = parseInt(prompt("Enter your numbers: "));
s += nums[i];
document.write("Number you chose: " + nums[i] + "<br />");
}
var ave = s / N;
document.write("Average: " + ave + "<br />");
</script>
Also if you don't need those input numbers, you can remove the nums array and use a simple var instead of it:
<script type="text/javascript">
var nums = new Array();
var N = prompt("How many numbers would you like to enter? ");
N = parseInt(N);
var i = 0, s = 0;
for(i = 0; i <= N - 1; i++)
{
var x = parseInt(prompt("Enter your numbers: "));
s += x;
document.write("Number you chose: " + x + "<br />");
}
var ave = s / N;
document.write("Average: " + ave + "<br />");
</script>
<script>
var nums = new Array();
var N = prompt("How many numbers would you like to enter? ");
N = parseInt(N);
var i = 0;
for (i = 0; i <= N - 1; i++) {
// convert string to integer
nums[i] = parseInt(prompt("Enter your numbers: "));
document.write("Number you chose: " + nums[i] + "<br />");
}
var sum = nums.reduce(function(prev, cur) {
return prev + cur;
}, 0);
var avg = sum / N;
console.log(avg);
</script>
First of all, you are able to define var i = 0 in your for loop, and i <= N - 1 is the same as i < N. The more simple way to write your loop would be.. for(var i = 0; i < N; i++) (also removing the var N = 0; from above).
Now it's not necessary to put the user's numbers into an array to get the average of them. All you need for the average is the sum of numbers and the amount of numbers.
Another cool thing about Javascript is that it freely converts the variable you are using into the type of variable that is appropriate for the context being used. This means that N = parseInt(N); is not necessary in your case, because it can only be treated as an integer in the loop.
If you take both of the above notes into consideration, you could use one of the following codes.
Solution 1: No array, just keeping the sum and amount of numbers
//Prompt the user how many numbers they would like to enter
var N = prompt("How many numbers would you like to enter? ");
//Set sum to 0, which gives us a base to add each number to it.
var sum = 0;
//Complete this loop the same amount of times as the user entered in the prompt
for (var i = 0; i < N; i++ ) {
//Add the users response to the sum of responses
sum += parseInt(prompt("Enter your numbers: "));
}
//Write into the document the sum of
document.write( "Avg. of entered numbers = " + sum / N);
However if you actually want to use an array as your question states, you could use the following code.
Solution 2: An array, while keeping track of the sum
//Prompt the user how many numbers they would like to enter
var N = prompt("How many numbers would you like to enter? ");
//Create an empty array to push elements to it
var nums = new Array();
//Set sum to 0, which gives us a base to add each number to it.
var sum = 0;
//Complete this loop the same amount of times as the user entered in the prompt
for (var i = 0; i < N; i++ ) {
//Get the users response to a variable
var response = parseInt(prompt("Enter your numbers: "));
//Add that variable to the sum
sum += response;
//And also push that variable to the array
nums.push(response);
}
//Write into the document the sum of the document
document.write( "Avg. of entered numbers = " + sum / nums.length);
If you noticed there we used nums.length instead of N. If you have a situation where you are unsure how many numbers the user will type in you could use the length of the array to see how many were entered.
Now here is an even simpler way you can do it while using arrays without keeping track of the sum of the array in the for loop. This takes advantage of the reduce function that many other answers have used.
Solution 3: Just an array!
//Prompt the user how many numbers they would like to enter
var N = prompt("How many numbers would you like to enter? ");
//Create an empty array to push elements to it
var nums = new Array();
//Complete this loop the same amount of times as the user entered in the prompt
for (var i = 0; i < N; i++) {
//Push users response to the original array
nums.push(parseInt(prompt("Enter your numbers: ")));
}
//Use the reduce function to get the sum of the array, and then divide it by the amount of elements in the array.
document.write( "Avg. of entered numddbers = " + (nums.reduce((a, b) => a + b) / nums.length));
Check this...
<title>
Title</title>
<script type="text/javascript">
function getSum(total, num) {
return total + num;
}
var nums = new Array();
var N = prompt("How many numbers would you like to enter? ");
N = parseInt(N);
var i = 0;
for (i = 0; i <= N - 1; i++) {
nums[i] = parseInt(prompt("Enter your numbers: "));
document.write("Number you chose: " + nums[i] + "<br />");
}
document.write("Avg. of entered numbers = " + (nums.reduce(getSum)) / nums.length);
</script>
<body>
</body>
Check this fiddle https://jsfiddle.net/45ab1812/1/

How to find the highest and lowest numbers from a loop in javascript

How can I add into this program to find the highest and lowest numbers? I have tried a few different things but it just keeps giving me the last number I enter as both.
<meta charset="UTF-8">
<title>Laskenta</title>
<script>
var yht=0; //sum
var luku=0; //number
var laske; //count
laske=Number(prompt("how many numbers would you like to add?"))
for (var i=0; i<laske; i++){luku = Number(prompt("give number", "number"));
yht=yht+luku;
}
while(i<laske);
document.write("the sum of the numbers you entered is " ,yht, "<br>");
document.write (" and the average is o " + yht/laske);
Ive translated most of it from Finnish and put next to what is still in Finnish the meanings next to it.
Any help would be greatly appreciated.
Thanks
The first set of operations addresses your desired to do these tasks in a loop, but you don't really need a traditional loop to do these tasks. The new spread operator along with Math.max and the Array.prototype.reduce() method can easily get you the max value, the sum or the average.
var result = null;
var nums = [];
// Remember, a propmt will always return a string, you must convert that
// to a number if you want to do math with it.
var count = parseInt(prompt("How many numbers do you want to work with?"), 10);
// Build up the input values into an array:
for(var i = 0; i < count; ++i){
nums.push(parseInt(prompt("Enter number " + (i + 1)),10));
}
// The "traditional" way to get the max value from a loop would be to
// compare the value that you are iterating and the next value in the
// array and store the higehr one:
var max = null;
var sum = 0;
for(var x = 0; x < nums.length-1; ++x){
max = (nums[x] > nums[x + 1]) ? nums[x] : nums[x + 1];
sum += nums[x];
}
console.log("Max number is: " + max);
var sum = 0;
for(var y = 0; y < nums.length; ++y){
sum += nums[y];
}
console.log("Sum is: " + sum);
console.log("Average is: " + sum / nums.length);
// *******************************************************************************
// But, we have much better ways of doing these jobs:
console.log("Max number is: " + Math.max(...nums));
result = nums.reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});
console.log("The sum is: " + result);
console.log("The average is: " + result / nums.length);
var yht=0; //sum
var luku=0; //number
var laske; //count
var highest;
var lowest;
laske=Number(prompt("how many numbers would you like to add?"))
for (var i=0; i<laske; i++){luku = Number(prompt("give number", "number"));
if (i == 0) {
highest = luku;
lowest = luku;
}
else {
if (luku > highest) highest = luku;
if (luku < lowest) lowest = luku;
}
yht=yht+luku;
}
while(i<laske);
document.write("the sum of the numbers you entered is " ,yht, "<br>");
document.write (" and the average is o " + yht/laske);
document.write("<br />Highest value="+highest);
document.write("<br />Lowest value="+lowest);
Add two variables in the code to track highest and lowest values entered. Set the first number entered to both highest and lowest. Then when a new low is encountered, replace lowest. When a new high value is encountered replace highest.

Using prompt, choose number of numbers, add that number of numbers to an array, then display total

I'm trying to load a prompt that asks how many numbers the user wants to enter, then a prompt will popup the amount of times they entered, and they will be able to enter a number each time that goes into an array and then one last alert box showing the sum.
How can I build this array and then get the total sum?
To get the first numberOfNumbers I used this:
function hello()
{
var numberOfNumbers=prompt("How many numbers would you like to add?")
alert(y)
}
var sum = [];
for (var i = 1; i <= numberOfNumbers; i++) {
sum.push(i);
}
Why would you build the array?
var numberOfNumbers = parseInt(prompt("How many numbers would you like to add?"));
if(isNaN(numberOfNumbers) || numberOfNumbers <= 0) {
alert("Invalid number!");
}
else {
var sum = 0, i;
for (i = 1; i <= numberOfNumbers; i++) {
sum += i;
}
alert(sum);
}
Also, as #JohnRummuel pointed out, in your code numberOfNumbers doesn't exist out of scope of the function block, so the for loop does not "see" it.
var numberOfNumbers = parseInt(prompt("How many numbers would you like to add?"));
alert(numberOfNumbers);
var sum = 0;
for (var i = 1; i <= numberOfNumbers; i++) {
sum += parseInt(prompt("Enter a number"));
}
alert("The sum of numbers you entered is " + sum);
Is this what you want to do?
function hello() {
var numberOfNumbers = prompt("How many numbers would you like to add?");
return parseint(numberOfNumbers, 10);
}
function sumNumbers() {
var numbers = [];
var number = 0;
var numberOfNumbers = hello();
for (var i = 1; i <= numberOfNumbers; i++) {
number = parseInt(prompt("Enter a number to add"), 10);
numbers.push(number);
}
alert(numbers.reduce(function(a, b) { return a + b; })) ;
}

Categories