Random number generator wont work with parseInt? - javascript

I've got this function that does a random number between 100 and 1 in JS and it adds it to the Score keeper, but the score keeper wont work. I even added parseInt for it to convert it from a string to an actually numbers int but it gives me NaN. But when I remove parseInt it gives me stacked numbers. Example: 50 + 100 will become 50100 not 150. Is there something wrong with the code? Here is the HTML and JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="pets.css">
</head>
<body>
<div>
<h1>Score Keeper</h1>
<button onclick="randGen()">Random Numbers</button>
<p id="paragraph"></p>
</div>
<h2 id="score"></h2>
<script src="pets.js"></script>
</body>
</html>
const scoreKeeper = document.getElementById('score');
scoreKeeper = 0;
function randGen() {
const p = document.getElementById('paragraph');
const generatedNumber = Math.floor(Math.random() * 100) + 1;
let currentNumber = parseInt(scoreKeeper.innerText) ?? 0
if (generatedNumber > 0) {
p.innerHTML = `Your number is: ${generatedNumber}`
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
return scoreKeeper;
}
}

Its a simple javaScript mistake. You are overwriting const. The aspect of const is that the value can NOT be overwritten. change it to let.
Also, you get an element document.getElementById("score") but then automatically overwrite it as 0. Also also, doing parseInt(scoreKeeper.innerText) ?? 0 checks if you can parseInt the innerText rather then if the innerText exist. You should check if it exist first and then parseInt it.
let scoreKeeper = document.getElementById("score");
function randGen() {
let p = document.getElementById("paragraph");
const generatedNumber = Math.floor(Math.random() * 100) + 1;
let currentNumber = scoreKeeper.innerText
? parseInt(scoreKeeper.innerText)
: 0;
if (generatedNumber > 0) {
p.innerHTML = `Your number is: ${generatedNumber}`;
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
}
}
Also, the return in this case in not needed. You do not return a value to any other function or place. You are modifying your h2 and p inner text directly from the function.
EDIT
You can make the code more readable and using less global variables by making an if check to check if the value is what you do not want and just do an empty return, and move the let scoreKeeper inside the function. Declare all other variables, besides the generatedNumber, after the check and return to only create variables and use up memory if the conditions are met.
function randGen() {
const generatedNumber = Math.floor(Math.random() * 100) + 1;
if (generatedNumber <= 0) return;
let scoreKeeper = document.getElementById("score");
let p = document.getElementById("paragraph");
let currentNumber = scoreKeeper.innerText
? parseInt(scoreKeeper.innerText)
: 0;
p.innerHTML = `Your number is: ${generatedNumber}`;
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
}

Related

How to use JavaScript Math.random() within HTML p tag

I am trying to print 1 random number within my <p> in HTML.
JavaScript:
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
document.getElementById("randomNum").innerHTML = randomNumber; // Sets content of <div> to number
return false; // Returns false just to tidy everything up
}
window.onload = number; // Runs the function on click
HTML:
<div class = card>
<div id="randomNum">
<h2>Header</h2>
<p>stats - [randomNumber] <br/> stat 2 - [randomNumber] </p>
</div>
</div>
(I could not get my HTML to post normally so I had to make it ugly. Sorry...)
My random number will print off to the side, and it is unable to print more within the same p. I was wondering if there is a way to place my random number from JavaScript within my p in HTML and keep all the css settings within the other div class card.
Thank you!
If I understand your question correctly, you want to place the random number in the p instead of the div, and have it append each time.
You should create an element each time with document.createElement and append it to the div, like this
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
var newNumber = document.createElement("p");
newNumber.innerText = randomNumber;
document.getElementById("randomNum").appendChild(newNumber);
return false; // Returns false just to tidy everything up
}
function number()
{
var minNumber = 1; // The minimum number you want
var maxNumber = 5; // The maximum number you want
var randomNumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
//document.getElementById("randomNum").innerHTML = randomNumber; // Sets content of <div> to number
var x = document.getElementsByClassName("randNum");
x[0].innerHTML = randomNumber;
x[1].innerHTML = randomNumber;
return false; // Returns false just to tidy everything up
}
window.onload = number; // Runs the function on click
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = card>
<div id="randomNum">
<h2>Header</h2>
<p>stats - <span class="randNum"></span> <br/> stat 2 - <span class="randNum"></span> </p>
</div>
</div>
</body>
</html>
You have to give the P element a ID, then do a document.getElementbyID(whatever you put the ID for in the P tag) = randomNumber Your Html should be
<p id="whatever you want"></p>
Hopefully that helps.

show random number < 0.8 not working properly

Hi I'm kinda new on JS so I tried to do this, I made this to test the random function and I want to show only random numbers below 0.8, but sometimes it shows above 0.8 also more than one time in a row, how do I fix it ?
This is my first post ever here, so sorry if I did something wrong.
Thanks. :)
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
if (rn() < 0.8) {
document.write(rn() + "<br>")
}
if (rn() > 0.8) {
x = 100
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>exp</title>
</head>
<body id="bd">
<h1 id="11"></h1>
</body>
<script src="exp.js"></script>
</html>
Your code makes two random number calls, each of which may have a different value. The fix is to use else to ensure only one branch fires:
let n = Math.random();
if (n < 0.8) {
document.write(n + "<br>")
}
else {
x = 100
}
Just because you've wrapped Math.random() in a function doesn't mean it fires only once. Each and every call to rn() will return a new value. The local variable a is initialized anew with each function call. It does not persist between calls.
In your original code around 16% of the time (80% x 20%) you'd fluke out and trigger both branches.
Assign the return value to a variable in order to hold the same value over different conditions.
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
const randomNumber = rn();
if (randomNumber < 0.8) {
document.write(randomNumber + "<br>")
}
if (randomNumber > 0.8) {
x = 100
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
The problem is that you're calling rn() multiple, and it returns different numbers each time. The result you test in if is not the same one that you display with document.write(), or the one that you test in the second if.
You need to save the number to a variable so you can test and display the same number.
Also, use else when you want to do something when the previous test failed.
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
var num = rn();
if (num < 0.8) {
document.getElementById("bd").innerHTML += (num + "<br>")
} else {
break;
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>exp</title>
</head>
<body id="bd">
<h1 id="11"></h1>
</body>
<script src="exp.js"></script>
</html>

How to generate set of arrays when clicking button, without disappearing the first one?

Im trying to learn js. Im starting playing with array by generating 6 combination numbers. This is working but i dont know how to output another combinations when I click the button. Any comment is appreciated. THanks
function getRandomNumber() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var arr = [];
while(arr.length < 8){
var myrandomnumber = Math.floor(Math.random(x) * y + 1);
if(arr.indexOf(myrandomnumber) === -1) arr.push(myrandomnumber);
}
if (x==""){
alert("Please enter a number");
}
else if (y==""){
alert("Please enter a number");
}
else{
document.getElementById("ok").innerHTML = arr;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RANDOM NUMBER JS</title>
<meta name="" content="">
<link rel="stylesheet" href="css/css/bootstrap.css">
<link rel="stylesheet" href="css/cssextra/csse1.css">
<script src="customscript.js"></script>
</head>
<body class="bg-light">
<br>
<p id="demo">Random Number</p>
<br><br>
<input type="number" id="num1" name="one"/ >
<input type="number" id="num2" name="two"/ >
<button onclick="getRandomNumber();">Generate random number</button >
<p id="ok"></p><br>
<p id="okok"></p>
</body>
</html>
Accumulate results
A easy yet crude solution would be appending the current text with <br> for line breaks:
const p = document.getElementById("ok");
p.innerHTML = p.innerHTML + (p.innerHTML === "" ? "" : "<br>") + arr.join(", ");
But this approach will notoriously perform badly as the text grows larger.
If you change the p elements into:
<div id="ok" class="text-container">
And replace the script's document.getElementById("ok").innerHTML = arr; into:
const p = document.createElement("p");
p.textContent = arr.join(", ");
document.getElementById("ok").appendChild(p);
And add css:
.text-container {
margin-top: 1em;
}
.text-container > p {
margin: 0;
}
Then you should have something working.
Also there are some things to address:
Math.random()
The function Math.random() does not take arguments, so your variable x does not have any effect.
If the intention is to x and y as a minimum and maximum value, try this from Math.random() - JavaScript | MDN:
function getRandomInt(min, max) {
var min = Math.ceil(min);
var max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
The min is inclusive and the max is exclusive. If x = 0 and y = 10, and you want the range to be [0-10], you can do getRandomInt(x, y + 1).
Make sure min is not greater than max.
Prevent infinite loop
Your loop will get stuck if the amount of possible unique integers is smaller than the number of array elements required for it to end.
More user input semantics
Variables x and y are tested before writing out the numbers, but after they have already been used to generate the numbers. In other words, the number creation process should be moved into the else block.
innerHTML expects a string and you are setting the array.
use document.getElementById("ok").innerHTML = arr.join(' ');
this will concatenate each element in the array with a space as glue

Adding sum of an array but getting NAN

I'm trying to create a working time clock that allows me to input the number of hours I study everyday and get the total. Am I using parseInt wrong?
<html>
<head>
<title>Time clock</title>
<meta charset="utf-8">
</head>
<body>
<h1 id="header">Time clock</h1>
<p id="greeting"></p>
<input type="text" id="inp"/>
<button onclick="sumit()">Click</button>
<p id="hours"></p>
<script>
greeting.innerHTML = 'How many hours have you studied?'
function sumit(){
let text = parseInt(document.getElementById("inp").value);
let hours = (document.getElementById("hours"));
let total = 0
for (i = 0; i < 10; i++){
total += parseInt(text[i]);
hours.innerHTML = `You have studied a total of ${text + total} hours.`
}
console.log(total)
console.log(text)
}
</script>
</body>
</html>
The text variable is already defined and assigned the value of parseInt. So your total += parseInt(text[i]) is trying to index a number type (e.g. total += 123[0]) which isn't possible. Instead, you can just do total += text, or you can remove the parseInt call when you declare text and then do total += parseInt(text).
With minimal changes, this should work:
function sumit() {
let text = parseInt(document.getElementById("inp").value) || 0;
let hours = document.getElementById("hours");
let total = 0;
total += text;
hours.innerHTML = `You have studied a total of ${total} hours.`;
}
Explanation
parseInt can return NaN, so we use the || operator to let it default to 0
You don't need to loop over anything to sum the number
Even if you were looping over anything, you don't use reference indexes on numbers like you tried to do with text[i]
You don't need to add total to text multiple times

I have a question about setting a variable "random" to a function to receive a random number between 1- whatever the user input

In the console, I checked that my variable maxAge, is set to the input of the user in the first box.
Then I checked my function getRandomInt worked, and truly get a random number between 1- whatever the user put in box.
For some reason that I don't understand I can't set a variable called
randomAge = getRandomInt()
Can someone explain to me why?
html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css.css">
<title>Document</title>
</head>
<body>
<h1>Guses The Age.
From 1 - <span id="secretage"></span>
</h1>
<p id="massageDisplay"></p>
<br>
<input id="gusesInput" type="number">
<input id="numInput" type="number">
<script src="script.js"></script>
</body>
</html>
js
var min = 1
var userInput = document.querySelector("#numInput")
var userGuses = document.querySelector("#gusesInput")
var randomAge = getRandomInt()
userInput.addEventListener("change", function() {
maxAge = Number(this.value)
ageDisplay.textContent = maxAge
})
function getRandomInt() {
return Math.floor(Math.random() * (maxAge - min)) + min;
}
// save random age as variable
// min and max can be set in (randomAge) closure var min=1
var userInput=document.querySelector("#numInput")
var userGuses=document.querySelector("#gusesInput")
/*
this assigns your function to the variable but it does not trigger the function.
var randomAge=getRandomInt()
*/
var randomAge = (function (){
var min = 0,
max = 0,
age = 0;
function setMinFunc(newNum){
return min = newNum;
}
function setMaxFunc(newNum){
return max = newNum;
}
function setRandomFunc(){
return Math.floor(Math.random() * (max - min )) + min;
}
function getAgeFunc(newNum){
return age;
}
function checkValsFunc(){
console.log('min value is ', min, '. max value is ', max, '. age is ', age);
}
return{
setMin: setMinFunc,
setMax: setMaxFunc,
setRandom: setRandomFunc,
gatAge: getAgeFunc,
checkVals: checkValsFunc
}
}());
randomAge.setMin(1);
userInput.addEventListener("change",function(){
maxAge=Number(this.value)
ageDisplay.textContent=maxAge
randomAge.setMax(maxAge);
randomAge.setRandom();
randomAge.checkVals();
})
// you can retrieve your random value by assigning it to a variable like this.
var myRandomVal = randomAge.gatAge();
You are missing many points in order for your code to work:
In the getRandomInt() function, maxAge is not defined. This variable should be declared at the same time of all other ones. But I suggest you to use two function parameters to have a minimum and maximum limit.
You are trying to attribute the returned result of getRandomInt() to randomAge but as maxAge is not defined outside your event handler... Moreover, if it was the case, randomAge would never change as you are not executing it in your event handler. You need to just define it at the beginning (at 0 for example), and to attribute the result call at change of your input.
Here is below a snippet that should work, with the corrections I suggested. I commented the changes I made, and the lines which are not useful for the snippet.
var min = 1;
var userInput = document.querySelector("#numInput");
//var userGuses = document.querySelector("#gusesInput");
var randomAge = 0; // Initializes here your random int variable.
userInput.addEventListener("change", function() {
maxAge = Number(this.value);
//ageDisplay.textContent = maxAge;
randomAge = getRandomInt(min, maxAge); // Attributes your random age to the variable.
console.log(randomAge);
})
// Added here two parameters for MIN and MAX integer.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
<input type="number" id="numInput" min="1">
var min = 1
var userInput = document.querySelector("#numInput")
var userGuses = document.querySelector("#gusesInput")
var randomAge ;
var maxAge;
userInput.addEventListener("change", function() {
maxAge = Number(this.value)
ageDisplay.textContent = maxAge
//should set the value in function
randomAge = getRandomInt();
//check the random value in console
console.log(randomAge);
})
function getRandomInt() {
return Math.floor(Math.random() * (maxAge - min)) + min;
}
// save random age as variable
i added this part of code in input event Listerine to get random value som missing like you should define maxAge
//should set the value in function
//randomAge = getRandomInt();
//check the random value in console
//console.log(randomAge);

Categories

Resources