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] + " ");
}
}
}
Related
Created a lottery number guesser sort of program that takes a number 1-10 and has the user guess the number, a total of 3 times, to win a "prize". In the lottery part of the program, I was able to get no problem but can't get the program to count the number of guesses and display the correct prize amount.
Here is the code I have:
<script>
var randomNum1 = Math.floor((Math.random() * 9) + 1);
var randomNum2 = Math.floor((Math.random() * 9) + 1);
var randomNum3 = Math.floor((Math.random() * 9) + 1);
console.log(randomNum1);
console.log(randomNum2);
console.log(randomNum3);
console.log(x);
var firstNum = false;
var secondNum = false;
var thirdNum = false;
var x = 0;
var moneyWon = 0;
firstNum = parseInt(prompt("Guess the first number."));;
secondNum = parseInt(prompt("Guess the second number."));;
thirdNum = parseInt(prompt("Guess the third number."));;
if((firstNum == randomNum1) || (firstNum == randomNum2) || (firstNum == randomNum3))
{
firstNum == true;
}
if(firstNum == true)
{
moneyWon = 100;
x++;
}
else{
moneyWon = 0;
}
if((secondNum == randomNum2) || (secondNum == randomNum1) || (secondNum == randomNum3))
{
secondNum == true;
}
if(secondNum == true)
{
moneyWon = 200;
x++;
}
else{
moneyWon = 100;
}
if((thirdNum == randomNum2) || (thirdNum == randomNum1) || (thirdNum == randomNum3))
{
thirdNum == true;
}
if(thirdNum == true)
{
moneyWon = 500;
x++;
}
else{
moneyWon = 200;
}
alert("The computer's numbers are " + randomNum1 + " " + randomNum2 + " " + randomNum3 +
"\nYour guesses were " + firstNum + " " + secondNum + " " + thirdNum +
"\nYou got " + console.log(x) + " right" +
"\nYou've won $" + moneyWon);
</script>
First thing im noticing:
You got " + console.log(x) + " right" +
You dont want the console.log() here, just the x
The second thing, you dont want to set moneyWon every time in the ifs, but rather do moneyWon += amount, just like you are doing with the x
Also, in the else (indicating the guess was incorrect), you dont want to set nor add to the amount (I would suggest deleting these 3 elses altogether):
else{ moneyWon = 0; }
and a minor thing - give meaningful names to properties, ie
var firstNum = false should be more like (is)firstNumberGuessed (the is indicates that this is a boolean
I see you are on the right track re this, but its good to learn not to be lazy about this stuff asap
EDIT: you can also throw out assigning true to firstNum, secondNum, thirdNum and just have this:
if((firstNum == randomNum1) || (firstNum == randomNum2) || (firstNum == randomNum3))
{
moneyWon += 100;
x++;
}
Well, I don't need to tell you what are the errors and what are causing them, as my friend Dejan already included them in his answer. In my answer, I am trying to implement his answer as well as some useful javascript methods which may make your work a lot more easier and faster as well.
First of all, arrays are your friend. I have made arrays for user inputs as well as random numbers and populating them using a for loop.
Next, as we are using arrays, we can use the includes() method to find the values among the random numbers. It reduces your if else conditions.
Next, I am using string interpolation to get the output message.
let randoms = [];
let nums = [];
let numbers = ["first", "second", "third"];
let winPrize = [100, 200, 500];
let losePrize = [0, 100, 200];
for(let i=0; i<3; i++){
randoms.push(Math.floor((Math.random() * 9) + 1));
nums.push(parseInt(prompt(`Guess the ${numbers[i]} number.`)));
}
let x = 0;
let moneyWon = 0;
for(let i=0; i<3; i++){
if(randoms.includes(nums[i])){
x++;
moneyWon+=winPrize[i];
}else{
moneyWon+=losePrize[i];
}
}
alert(`The computer's numbers are ${randoms[0]}, ${randoms[1]} and ${randoms[2]}. \nYour guesses were ${nums[0]}, ${nums[1]} and ${nums[2]}. \nYou got ${x} right. \nYou've won $${moneyWon}`);
I believe that if we follow such practices, our code will remain short as well as easily readable and maintainable.
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();
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.
First day of school, we're supposed to make a hangman game. I've been staring at the logic in my while loop for hours now. I can't get my loop to say yes, the word(newWord) does contain the guess. I always get the prompt that it is incorrect, and then all heck breaks loose. I've tried 25 different ways. I know it's all busted beyond repair now, but if anyone can get me going the right direction, I'd be eternally grateful.
let words = ["skate", "guitar", "laugh", "party", "shirt"]
let wordValue = Math.floor(Math.random() * 4) + 1;
let newWord = words[wordValue];
let misses = 0;
let rightGuess = 0;
let wrongGuess = 0;
var answerLines = [];
for (let i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
let remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
let guess = prompt("Guess a letter, any letter!");
for(let j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
rightGuess++
}
else { wrongGuess++ }
if (rightGuess != 0) {
answerLines[j] = guess;
remainingLetters--;
}
else {
misses++
(alert("That was is incorrect. You have " + misses + " of 6 misses."));
Your logic for processing the guess is a little off. Try this:
var words = ["skate", "guitar", "laugh", "party", "shirt"]
var wordValue = Math.floor(Math.random() * 4) + 1;
var newWord = words[wordValue];
console.log("Word is: " + newWord);
var misses = 0;
var answerLines = [];
for (var i = 0; i < newWord.length; i++) {
answerLines[i] = "_";
}
var remainingLetters = newWord.length;
while (remainingLetters > 0 && misses < 6) {
alert(answerLines.join(" "));
var guess = prompt("Guess a letter, any letter!");
var matchesNone = true; //boolean to track if guess matched any letters
for (var j = 0; j < newWord.length; j++) {
if (newWord[j] === guess) {
answerLines[j] = guess;
remainingLetters--;
matchesNone = false; //the guess matched atleast one letter
}
}
if (matchesNone) { //the guess matched none of the letters
misses ++;
alert("That was is incorrect. You have " + misses + " of 6 misses.");
}
}
if(remainingLetters>0) {
alert("You failed to guess the word: " + newWord);
}else{
alert("You guessed the word! It was: " + newWord);
}
I wrote this little piece of code to count the numbers of negative, zero, and positive elements in an array of number. When I run the code, the browser won't respond and I have to kill it! Any help will be appreciated. Thank you.
<script type = "text/javascript">
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var arrayNum1 = promptArrayNum.toString();
var arrayNum2 = [arrayNum1];
var arrayNum3 = counter(arrayNum2);
function counter(number){
var count;
var countNeg = 0;
var countPos = 0;
var countZero = 0;
for (var i = 0; i <= arrayNum2.length; i++)
{
switch (true){
case (arrayNum2[i] < 0): countNeg++;
document.write("Negative elements = " + countNeg);
break;
case (arrayNum2[i] = 0): countZero++;
document.write("Zero elements = " + countZero);
break;
case (arrayNum2[i] > 0): countPos++;
document.write("Positive elements = " + countPos);
break;
default: {document.write("Array is invalid");}
}
}
return count;
}
First off, it isn't array what you're operating on. Just split on the ,
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var arr = promptArrayNum.split(",");
Also, your code can be more efficient as in
var numOf0s = arr.filter(function(e){ return e == 0 }).length,
numberOfPositives = arr.filter(function(e){ return e > 0 }).length,
numberOfNegatives = arr.filter(function(e){ return e < 0 }).length;
Although your algorithm is not correct. The reason of infinite loop is line
case (arrayNum2[i] = 0): countZero++;
you have used assignment operator and you are looping through arrayNum2. its size is increasing in every loop.
instead it should be
case (arrayNum2[i] == 0): countZero++;
Here's a simplified working version of your code
use split to generate your input array
use if statements rather than switch
arrayNum2[i] = 0 is assignment, not equality comparison (use === (strict equality)
moved alerts outside the loop
http://jsfiddle.net/hk6uger4/2/
var input = prompt("Enter an array of numbers (Separated by comma): ");
var arr = input.split(',');
var count;
var countNeg = 0;
var countPos = 0;
var countZero = 0;
var i = 0;
for (i = 0; i <= arr.length; i++) {
if (arr[i] < 0) {
countNeg++;
}
if (arr[i] === 0) {
countZero++;
}
if (arr[i] > 0) {
countPos++;
}
}
alert("Negative elements = " + countNeg);
alert("Zero elements = " + countZero);
alert("Positive elements = " + countPos);
It works now! I took me more than 2 hours to figure it out. I'm a newbie to JS.
<script type = "text/javascript">
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var arrayNum = promptArrayNum.toString();
var arrayData = [arrayNum];
arrayData = arrayNum.split(",");
var arrayImplement = counter(arrayData);
function counter(number){
var count;
var countNeg = 0;
var countPos = 0;
var countZero = 0;
for (var i = 0; i < arrayData.length; i++){
switch (true){
case (arrayData[i] < 0): countNeg++;
break;
case (arrayData[i] == 0): countZero++;
break;
case (arrayData[i] > 0): countPos++;
break;
default: {document.write("Array is invalid");}
}
}
document.write("The array of numbers entered is: " + arrayData, "<br/>");
document.write("Negative elements = " + countNeg, "<br/>");
document.write("Zero elements = " + countZero, "<br/>");
document.write("Positive elements = " + countPos, "<br/>");
return count;
}
oh, weird code. Try this one:
var promptArrayNum = prompt("Enter an array of numbers (Separated by comma): ");
var data = promptArrayNum.split(",");
data = data.map(function(item){if(!item)return 0;else return parseInt(item.trim())});
for(var i = 0; i < data.length; i++){
var item = data[i];
if(item == 0){alert("item == 0")}
else if(item > 0) { alert("item > 0")}
else alert("item < 0")
}