Javascript not rounding properly - javascript

I made a simple number guessing game in javascript which goes from 1 to 100.
My problem is that everything works, except when I type a decimal number from 100 to 101. I want my code to give me the "Please enter a number from 1 to 100" message then, but it doesn't.
How do I get Javascript to round this properly?
let randomNumber = Math.floor(Math.random() * 100); // Random number
function guess() {
let inp = document.getElementById("number").value; // Reading input
let inpRounded = Math.floor(inp);
// Random number is higher
if (inpRounded < randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "Higher";
}
// Random number is lower
else if (inpRounded > randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "Lower";
// Input matches random number
} else if (inpRounded == randomNumber && inpRounded >= 1 && inpRounded <= 100) {
document.getElementById("result").innerHTML = "You won!";
}
// Input is weird
else if (inpRounded == null) {
document.getElementById("result").innerHTML = "Please enter a valid number";
}
// Input is lower than 1 or higher than 100
else if (inpRounded < 1 || inpRounded > 100) {
document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
}
// Other issue
else {
document.getElementById("result").innerHTML = "Error"
}
}
<h2>Enter a number from 1 to 100</h2>
<input type="number" placeholder="Type your guess here" id="number">
<input type="button" value="Go!" onclick="guess()">
<p id="result"></p>

Don't round the number initially, otherwise you'll lose the decimal information you need when you want to reject values between 100 and 101.
function guess() {
const value = document.getElementById("number").value; // Reading input
const numValue = Number(value);
if (numValue < 1 || numValue > 100) {
document.getElementById("result").textContent = "Please enter a number from 1 to 100";
return;
}
const inpRounded = Math.floor(numValue);
// etc

Just put this code first before you check other things.
if (inpRounded == null) {
document.getElementById("result").innerHTML = "Please enter a valid number";
return;
}
if (inpRounded < 1 || inpRounded > 100) {
document.getElementById("result").innerHTML = "Please enter a number from 1 to 100";
return;
}

Related

terminate a prompt dialogue box when user enters "-1" [javascript]

I am having some troubles with js code. I need to prompt the user to enter a valid number (between 0 and 120). If the entry is invalid, it should just display the starting prompt. However, if the user enters "-1", it should terminate the dialogue box.
My dialogue box does not terminate when I enter "-1". What could be the issue? Here is my code
let numGrade; //variable that holds number grade entry
let letter; //this variable holds grade as a letter
//this function checks whether our grade within the range
numGrade = window.prompt("Enter number grades from 0 to 120\nOr enter - 1 to end entries")
if (numGrade == -1){
return false;
}
else if(numGrade<=120 && numGrade>=0){
//calling replaceGrades function, passing a number grade to convert it to a letter grade
// store a grade letter in "final"
final = replaceGrades(numGrade)
//display a number grade and letter grade
alert("Number grade = " + numGrade + "\nLetter grade = " + final)
//this function takes in number grade as a parameter--
// and return a letter grade
function replaceGrades(grade) {
let letterGrade; //variable that returns a letter grade
//if else-if to convert number grades to letter grades{
if (grade >= 100 && grade <= 120) {
return letterGrade = "A";
} else if (grade >= 80 && grade <= 99) {
return letterGrade = "B";
} else if (grade >= 70 && grade <= 79) {
return letterGrade = "C";
} else if (grade >= 60 && grade <= 69) {
return letterGrade = "D"
} else {
return letterGrade = "F";
}
}
}
else {
numGrade = window.prompt("Enter number grades from 0 to 120\nOr enter - 1 to end entries")
}

trying to turn my working code into a function

I am trying to turn this working code I have into a function for a course I am taking.
<!DOCTYPE html>
<html>
<body>
<script>
var entry;
var letterGrade;
var total = 0; // you forgot to set the start value for total
var entryCount = 0; // also for entry count you must initialize first.
// add the error string here so we dont have to duplicate it in the code.
var errorString = "Entry must by a valid number from 0 through 100\nOr enter 999 to
end entries";
do {
// get something from user
entry = prompt("Enter number grade from 0 through 100\nOr enter 999 to end entries",
999);
// the user may also enter something that is not a number
if(isNaN(entry)){ // check if it is not a number
alert(errorString); //show error if not a number
}else{
// you now know you have a number so you can parse it
entry = parseInt(entry); // convert to number
// now check for a valid number
if (entry >= 0 && entry <= 100) {
// number is in valid range check each grade
if (entry < 50) {
letterGrade = "F";
}else
if (entry < 70) {
letterGrade = "D";
}else
if (entry < 80) {
letterGrade = "C";
}else
if (entry < 90) {
letterGrade = "B";
}else
if (entry <= 100) {
letterGrade = "A";
}
total += entry; // add the total
entryCount += 1; // add ont to count
// display entry and grade
alert("Number grade = " + entry + "\nLetter grade = " + letterGrade);
}else // if not in valid range check if its 999
if (entry != 999) {
alert(errorString); // no show error
}
}
}while (entry != 999); // do this till 999 is entered
</script>
</body>
</html>
The code itself is doing what it is supposed to do but according to the assignment I have to call a function like
function myFunction(){}
I am not crazy about hitting 999 to break the prompt either if anyone has any suggestions bout that as well it would be greatly appreciated
Here I am calling function normally. You can add this function to be called on a certain event like page load or button click.
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
var entry;
var letterGrade;
var total = 0; // you forgot to set the start value for total
var entryCount = 0; // also for entry count you must initialize first.
// add the error string here so we dont have to duplicate it in the code.
var errorString = "Entry must by a valid number from 0 through 100\nOr enter 999 to end entries";
do {
// get something from user
entry = prompt("Enter number grade from 0 through 100\nOr enter 999 to end entries",
999);
// the user may also enter something that is not a number
if (isNaN(entry)) { // check if it is not a number
alert(errorString); //show error if not a number
} else {
// you now know you have a number so you can parse it
entry = parseInt(entry); // convert to number
// now check for a valid number
if (entry >= 0 && entry <= 100) {
// number is in valid range check each grade
if (entry < 50) {
letterGrade = "F";
} else
if (entry < 70) {
letterGrade = "D";
} else
if (entry < 80) {
letterGrade = "C";
} else
if (entry < 90) {
letterGrade = "B";
} else
if (entry <= 100) {
letterGrade = "A";
}
total += entry; // add the total
entryCount += 1; // add ont to count
// display entry and grade
alert("Number grade = " + entry + "\nLetter grade = " + letterGrade);
} else // if not in valid range check if its 999
if (entry != 999) {
alert(errorString); // no show error
}
}
} while (entry != 999); // do this till 999 is entered
}
myFunction();
</script>
</body>
</html>

I'm writing a guessing game in javascript. I don't know how to validate that the number is inbetween 0 and 100 through the code

The exercise I'm doing is to write a guessing game.
It asks for you to write a function for the user to enter a guessed number, write a second function to validate the code, write a third function that checks the number and tells the user if it's too high or too low.
My problem is that when I get to the too high or too low part it stops validating whether the number is in between 1 and 100. I've tried everything that I know and I'm still really confused. The code worked otherwise before I put in the ValidNUm variable.
I feel like this could be an easy answer and I'm not getting it so I'm sorry. point is I need the guessing game to validate the number, if it's wrong they will enter a number till it is correct, then it tells them wether that validated number is too high or too low.
What happened before is that it validates the number but doesn't pass on the valid number to be assessed.
var GuessedNumber, RandomNum, ValidNum;
RandomNum = 24; //Math.floor((Math.random() * 100) + 1);
GuessedNumber = EnterGuess();
ValidNum = ValidateGuess(GuessedNumber);
NumberCheck(GuessedNumber, RandomNum, ValidNum);
function EnterGuess() {
var ArgGuessNum;
ArgGuessNum = parseFloat(prompt("Please guess a number between 1 and 100"));
return ArgGuessNum;
}
function ValidateGuess(ArgGuessNum) {
var ArgValidNum;
while (ArgGuessNum < 1 || ArgGuessNum > 100) {
ArgGuessNum = parseFloat(
prompt("Please guess a valid number between 1 and 100")
);
}
if (ArgGuessNum > 0 || ArgGuessNum < 100) {
ArgValidNum = ArgGuessNum;
return ArgValidNum;
}
alert("valid number");
}
function NumberCheck(ArgGuessNum, ArgRandomNum, ArgValidNum) {
var ctr = 1;
while (ArgValidNum != ArgRandomNum) {
if (ArgValidNum > ArgRandomNum) {
ArgGuessNum = parseFloat(
prompt("Uh-Oh the number is too high! enter another guess")
);
ValidateGuess(ArgGuessNum);
} else if (ArgValidNum < ArgRandomNum) {
ArgGuessNum = parseFloat(
prompt("Uh-Oh the number is too low! enter another guess")
);
ValidateGuess(ArgGuessNum);
}
ctr++;
}
alert("you took " + ctr + " guesses");
}
When you validate the guessed number inside the NumberCheck(...) you are not assigning the resulting 'valid' number back to a variable (so it's never considered in the next iteration of the loop.
You need to add something like ArgValidNum = ValidateGuess(ArgValidNum);
I also went and simplified the NumberCheck(...) since you are comparing only two numbers: the one guessed and the 'randomly' created at the beginning.
See demo code below
var GuessedNumber, RandomNum, ValidNum;
RandomNum = 24; //Math.floor((Math.random() * 100) + 1);
GuessedNumber = EnterGuess();
ValidNum = ValidateGuess(GuessedNumber);
NumberCheck(RandomNum, ValidNum);
function EnterGuess() {
return parseFloat(prompt("Please guess a number between 1 and 100"));
}
function ValidateGuess(ArgGuessNum) {
var ArgValidNum;
while (ArgGuessNum < 1 || ArgGuessNum > 100) {
ArgGuessNum = parseFloat(
prompt("Please guess a valid number between 1 and 100")
);
}
if (ArgGuessNum > 0 || ArgGuessNum <= 100) {
ArgValidNum = ArgGuessNum;
return ArgValidNum;
}
console.log("valid number");
}
function NumberCheck(ArgRandomNum, ArgValidNum) {
var ctr = 1;
while (ArgValidNum !== ArgRandomNum) {
if (ArgValidNum > ArgRandomNum) {
ArgValidNum = parseFloat(
prompt("Uh-Oh the number is too high! enter another guess")
);
ArgValidNum = ValidateGuess(ArgValidNum);
} else if (ArgValidNum < ArgRandomNum) {
ArgValidNum = parseFloat(
prompt("Uh-Oh the number is too low! enter another guess")
);
ArgValidNum = ValidateGuess(ArgValidNum);
}
ctr++;
}
alert("you took " + ctr + " guesses");
}

Having trouble displaying my number using javascript

I have to convert from decimal to binary and it requires at least 3 functions and it has to be displayed in HTML. This is what I've got so far and can't figure out how to make it display properly?
// Prompt user for number between 1-1000
let input = parseInt(prompt("Enter a number between 1 and 1000", "50"));
function store() {
let quotient = [];
let answer = quotient.reverse();
return answer;
}
function check() {
while (input != 0) {
if (input < 1000 && input % 2 != 0) {
return quotient.push("1");
input = input / 2;
}
else if (input < 1000 && input % 2 == 0) {
return quotient.push("0");
input = input / 2;
}
}
}
function display() {
document.getElementById("displayNumber").innerHTML = answer;
}
display();
<h1 id="displayNumber"></h1>
Here is the fixed script, I hope this helps.
function check(input, quotient) {
while (input != 0) {
if (input < 1000 && input % 2 != 0) {
quotient.push("1");
input = parseInt(input / 2);
}else if (input < 1000 && input % 2 == 0) {
quotient.push("0");
input = parseInt(input / 2);
}
}
}
function display() {
let input = parseInt(prompt("Enter a number between 1 and 1000", "50"));
let quotient = [];
check(input, quotient);
let answer = quotient.reverse().join('');
document.getElementById("displayNumber").innerHTML = answer;
}
display();
Currently, you are just creating the function store and check but not actually calling them.
However, if all you are wanting to do is to display the input as binary, you can use the toString function, passing in the base you desire.
Im not sure what you want to display if the number is outside of the range 1-1000. So I just put "Invalid input". You can add some more checks for if it is NAN ect
<!DOCTYPE html>
<html>
<h1 id="displayNumber"></h1>
<script>
// Prompt user for number between 1-1000
let input = parseInt(prompt("Enter a number between 1 and 1000", "50"));
function display() {
if (input < 1 || input > 1000) {
document.getElementById("displayNumber").innerHTML = "Invalid input";
} else {
document.getElementById("displayNumber").innerHTML = input.toString(2);
}
}
display();
</script>
</html>
Here is updated snippet :
function check(input) {
let quotient = [];
while (input != 0) {
if (input < 1000 && input % 2 != 0) {
input = input / 2;
}
else if (input < 1000 && input % 2 == 0) {
input = input / 2;
}
quotient.push(input);
}
return quotient;
}
function display() {
let input = parseInt(prompt("Enter a number between 1 and 1000", "50"));
var answer = check(input);
document.getElementById("displayNumber").innerHTML = answer;
}
display();
<h1 id="displayNumber"></h1>
In display function, you are assigning answer to innerHTML but not calling your check function.
<html>
<h1 id="displayNumber"></h1>
<script>
let input = parseInt(prompt('Enter a number between 1 and 1000', '50'));
function check(input) {
let quotient = [];
while (input > 0) {
quotient.push(input % 2);
input = parseInt(input / 2);
}
return quotient.reverse().join('');
}
function display() {
if (input >= 1 && input <= 1000) {
document.getElementById("displayNumber").innerHTML = check(input);
}
}
display();
</script>
</html>

JavaScript: Both dialog boxes show, even if the user enters incorrectly

This is a simple JavaScript/HTML guessing game. The only problem I have is that when the user enters a number/letter other than 1-6, the "error" message should pop-up — and it does, but then the game goes on and it still tells you whether you're a winner or not. This is the code that I have.
function jsFunc() {
var number = Math.ceil (Math.random() * 6) + 1;
var guessNum = 0;
guessNum = document.getElementById("num").value;
if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
alert ("Must be a number between 1 and 6. Please re-enter!");
}
if (number == guessNum)
alert("Congratulations, You Win!!!");
else
alert("Aw, You Lose..");
}
You can just add if else to make it work
Please refer snippet
function jsFunc() {
var number = Math.ceil (Math.random() * 6) + 1;
var guessNum = 0;
guessNum = document.getElementById("num").value;
if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
alert ("Must be a number between 1 and 6. Please re-enter!");
}else if (number == guessNum){
alert("Congratulations, You Win!!!");
}
else{
alert("Aw, You Lose..");
}
}
<input id ="num"/> <button onClick="jsFunc()">Submit</button>
You should be doing else-if
function jsFunc() {
var number = Math.ceil (Math.random() * 6) + 1;
var guessNum = 0;
guessNum = document.getElementById("num").value;
if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
alert ("Must be a number between 1 and 6. Please re-enter!");
}
else if (number == guessNum)
alert("Congratulations, You Win!!!");
else
alert("Aw, You Lose..");
}
if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
alert ("Must be a number between 1 and 6. Please re-enter!");
}
else if (number == guessNum)
{
alert("Congratulations, You Win!!!");
}
else
{
alert("Aw, You Lose..");
}
You if/else logic needs to be one continuous block. Because in your original code, your second IF get evaluated no matter what!

Categories