JavaScript how to ensure user enters a number between 1 and 100 - javascript

Hello i want the user to enter a number between 1 and 100 any higher i want it to display array out of bounds and not add the number to the array here is what i have and it works but when u enter in another number it says NAN
for(var i = 0; Repeat !== 'n'; i++){
Student.push(prompt("Enter Student Name: "));
Mark.push(parseInt (prompt("Enter Student mark: ")));
//Check if Mark entered is not out of bounds and gives a grade
if (Mark[i] <0 || Mark[i] >100){
alert("Grate out of bounds");
Mark.splice(i);//Removes array if out of bounds
}else if (Mark[i] >= 83){
getGrade.push("A");
A++;
}else if (Mark[i] >= 70){
getGrade.push ("B");
B++;
}else if (Mark[i] >= 50){
getGrade.push ("C");
C++;
}else if (Mark[i] >= 0){
getGrade.push ("F");
F++;
//If mark is not a number
}else if (isNaN(Mark)){
alert("Must input numbers");
}
Repeat = prompt ("Do you want to enter another student: y/n");
}

When you enter an incorrect value, the array is no longer in sync with i. For example, if you enter (Bob and 1000) for the first grade, consider what gets stored into the variables after the call to Mark.splice(i):
Student = [Bob]
Mark = []
Now Mark is empty, and i has been incremented to 1. Let's say you now enter values Johnny and 50. Your variables look like this:
Student = [Bob, Johnny]
Mark = [50]
Notice that when your code is validating the grade, there is no Mark[1], because the array only contains one value and i is looking at the second entry - thus NaN. Also, you have more entries in Student than you do in Mark.
As a general principle, you should not "commit" the data until you have finished all your validation logic. So store the entered amounts in temporary variables, check them, and then finally add them to the array at the end once you have good input data:
var entryStudent = prompt("Enter Student Name: ");
var entryMark = parseInt (prompt("Enter Student mark: "));
//Check if Mark entered is not out of bounds and gives a grade
...
//Once you have determined the values are valid, add them to the array
if (valid) {
Student.push(entryStudent);
Mark.push(entryMark);
} else {
// make sure i is moved back to previous entry so you don't skip one
i--;
}
This code isn't complete (for example, you need to figure out how to determine whether valid is true or false), but it should give you the general idea.

I would suggest 2 things -
Make your "isNaN" check before any other checks (so you wouldn't insert wrong values).
Store the parseInt result in a variable, make all the checks on that variable, and only if it passes - push it into Marks. That way you can avoid holding the i reference.
Something like this:
var grade, name;
for (var i = 0; Repeat !== 'n'; i++) {
name = prompt("Enter Student Name: ");
grade = parseInt(prompt("Enter Student mark: "));
// check if grade entered is a number
if (isNaN(grade)) {
alert("Must input numbers");
continue;
}
// check if grade entered is not out of bounds
if (grade < 0 || grade > 100) {
alert("Grade out of bounds");
continue;
}
// store the data
Student.push(name);
Mark.push(grade);
if (grade >= 83) {
getGrade.push("A");
A++;
} else if (grade >= 70) {
getGrade.push("B");
B++;
} else if (grade >= 50) {
getGrade.push("C");
C++;
} else if (grade >= 0) {
getGrade.push("F");
F++;
}
Repeat = prompt("Do you want to enter another student: y/n");
}

Related

Javascript : problem with while loop that does not work

In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();

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")
}

The score in my JavaScript quiz application it not storing properly. What is wrong with the syntax?

The majority of the code seems to be working. The problem is that it keeps returning the error message that I set in the if statement for calculating the final score message as the final else clause. I'm not sure how to see the value of what is actually being stored in the variable at any given time while the application is running.
var score = 0; // to store the correct answers
//List of answers
var answerOne = 'BLUE';
var answerTwo = 'GREEN';
var answerThree = 'PRINCIPLE';
var answerFour = 'MONEY';
var answerFive = 'WILLY WONKA';
// The questions and their verification protocol
var questionOne = prompt('What is the color of the sky?');
//Conditional statement matching user input to correct answer.
if (questionOne.toUpperCase === answerOne) {
score+= 1;
}
var questionTwo = prompt('What is the color of grass?');
//Conditional statement matching user input to correct answer.
if (questionTwo.toUpperCase === answerTwo) {
score+= 1;
}
var questionThree = prompt('What is the most powerful force?');
//Conditional statement matching user input to correct answer.
if (questionThree.toUpperCase === answerThree) {
score+= 1;
}
var questionFour = prompt('What makes the world go round?');
//Conditional statement matching user input to correct answer.
if (questionFour.toUpperCase === answerFour) {
score+= 1;
}
var questionFive = prompt('Who can take a sunrise and sprinkle it with dew?');
//Conditional statement matching user input to correct answer.
if (questionFive.toUpperCase === answerFive) {
score+= 1;
}
//Final score-providing message to user
if (score = 0) {
alert('Wow, you suck. No crown for you! You had ' + score + 'correct answers!');
} else if (score <= 2 && score > 1) {
alert('You were not the worst, but certainly not the best. You earned a bronze crown with ' + score + ' correct answers!');
} else if (score <= 4 && score > 3) {
alert('You did a pretty good job! You earned a silver crown with ' + score + ' correct answers!');
} else if (score === 5) {
alert('Congratulations! You have successfully answered all questions correctly! You have earned a gold crown with ' + score + ' correct answers!');
} else {
alert('ERROR!')
}
There are a number of issues with this code.
1) toUpperCase is a string function and should be used like:
if (questionFour.toUpperCase() === answerFour) {...
2) In your if/then statement your are assigning 0 to score, not checking that score equals 0. To do that:
if (score === 0) {
3) Finally you need to watch your if/then condition ranges.
This doesn't check if score is 1:
(score <= 2 && score > 1)
This does check if score is 1:
(score >= 1 && score <= 2)
Here's the corrected code.
toUpperCase is a method and, as such, should be written per this example:
questionOne.toUpperCase()
you used assignment operator not the ==.
if(score==0)
to see the value of score add console.log(score) above that.

Why does Math.floor(Math.random()) function always return "0"?

I am writing a program that chooses a random number between 0 and 1 and then enters a while loop until the random number generator selects a value more than .5. Every time I run the program, the program returns 0 and loops infinitely until it crashes. Why is this occurring? Shouldn't Math.floor(Math.random()) eventually select a number higher than .5?
var randomNumber = Math.floor(Math.random());
while(randomNumber < .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
if (name === "Yes") {
console.log("Good jorb!");
} else if(name === "No.") {
console.log("Go away!!!!!");
else {
console.log("I have no idea");
}
var randomNumber = Math.floor(Math.random());
}
This line almost always return 0 and that is why it does not get into the while.
var randomNumber = Math.floor(Math.random());
Math.random() return float values lower than 1 starting from 0 ... and with Math.floor you are getting the int part which indeed is 0
Your variable randomNumber was already initialized with your first line, to change it's value simply use randomNumber = newValue where newValue is the value you wish to set it to, using a method or hardcoded value. You do not need to use the var keyword again.
Also using Math.floor method on Math.random will always return 0, as Math.random will return a number between 0 and 1, which will floor to 0.
You were missing the closing bracket on your while loop.
I cleaned you code up a little to chain your if boolean operators, although there are better ways to construct this code.
var randomNumber = Math(Math.random());
while(randomNumber > .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
if (name === "Yes" || name === "yes" || name === "Yes." || name === "yes." || name === "Yup" || name === "Yup." || name === "yup." || name === "yup")
{
console.log("Good jorb!");
}
else if(name === "No." || name === "No" || name === "no" || name === "no." || name === "nope" || name === "nope." || name === "Nope" || name === "Nope.")
{
console.log("That's too bad.");
}
else
{
console.log("I don't know, man. I don't know");
}
randomNumber = Math(Math.random());
};// Close your while loop.
Your while loop will never run.
Math.random() returns a number n where 0 <= n <1
Math.floor(n) returns n rounded towards zero.
so your variable randomNumber will always equal zero.
you could also replace your if statements with an array of values to check.
Then look up the index of name in that array.
if the index is -1 it doesn't exist otherwise log "Good jorb!"
var randomNumber = Math.random();
while(randomNumber > .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
var yesArray = ["Yes", "yes", "Yes.", "yes.", "Yup", "Yup.", "yup.", "yup"];
if(yesArray.indexOf(name) == -1) {
console.log("I don't know, man. I don't know");
} else {
console.log("Good jorb!");
}
randomNumber = Math.random();
}
There are several reasons:
Math.floor(Math.random()), will always be zero so the loop will never start. Math.random() will give a number between 0 and 1 and you are flooring that one that means you are always rounding off down, which means zero.
If you want the while to stop, it is better to break; when the condition is right.
This code will work:
var randomNumber = Math.random();
while(randomNumber > .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
if (name === "Yes") {
console.log("Good jorb!"); break;
} else if(name === "Nope.") {
console.log("Okay that is fine.");
} else {
console.log("I don't know, man. I don't know");
}
randomNumber = Math.random();
}
But now it does not just depend on the answer whether the loop will continue but also on randomNumber.
Try this: (Sorry if I got any of the counts wrong on the long expletive... there were a lot of them...)
while(true){
var name=prompt("Do you want to play a game? Like checkers or something?");
if(name.search(/^[yY](es|up)\.?$/)!=-1){
console.log('Good jorb!');
}else if(name.search(/^[nN]o(pe)?\.?$/)!=-1){
console.log('F'+'U'.repeat(12)+'C'.repeat(13)+'K'.repeat(9)+' Y'+'O'.repeat(11)+'U'.repeat(18)+'!'.repeat(12));
}else{
console.log("I don't know, man. I don't know");
}
if(condition){
break;
}
}
Just to clarify about the regular expressions: They essentially look for the different forms of the word with capitalization or no and punctuation or no representing the full word (^ is the beginning of the string and $ is the end of the string). That should save you a lot of trouble.
Oh, and try to avoid while(true) for real development practices. for(var i=0;i<2e7;i++) or something similar is a better practice, but i figure if it's just for command line, that should be fine.

javascript keeps skipping my if statement thats inside two loops

Ok so im talking in some unput from the user, it must be 4 numbers, and the digits must not be the same. so everything is working accept the part where i check the 4 numbers against each other. i put the string into an array and then compare the array, by
checking the first one against the 2nd, 3rd, 4th,
then i check the second one against the 3rd, and 4th
then i check the third number against the 4th
My issue is the if statement will not work no matter what i try it gets bypassed everytime. I add random returns into the code to see where it goes and it always returns 12 no matter what even if the numbers i enter are 1111 it still passes.
Ive spent hours trying different stuff please help me!!
function validate(guess){
var user_guess = guess;
var valid = true;
var counter = 0;
parseFloat(user_guess);
if(user_guess.length == 4){
if((user_guess == null) || (isNaN(user_guess))){
validation_alert();
}else{
var guess_string = toString(user_guess);
var guess_array = guess_string.split('');
var guess_array2 = guess_array;
for(var i = 0; i < 3; i++){
counter = i + 1;
for(c = counter; c < 4; c++){
if(guess_array[i] == guess_array2[c]){
return 11;
valid = false;
validation_alert();
}
}
}
if(valid == true){
return 12;
}else{
return 13;
validation_alert();
}
}//if null
}else{
validation_alert();
}//if 4 end tag
}// function close
Just to prove to you that JavaScript uses function scope and not block scope (if else for ...) which means every var you declare moves automatically to the top of the current function it's running in.
Also note that when you return something you will exit the current function and not execute anything after that.
If you check against length you can be sure it's going to be a number so use === instead which checks against it's type (number, string, bool) as well.
Your 2 first if statements should be reversed I think. In anycase user_guess == null will never validate as the previous if checks on the length === 4.
Normally when you use return every block scope should return something. I haven't edited this but that's expected in strict javascript.
It seems more logical to start with valid=false and you will only set it to true when you are sure it's true. I'll leave that up to you.
function validate(guess){
var user_guess = parseFloat(guess),
guess_string,
guess_array,
guess_array2,
valid = true,
counter = 0,
i = 0,
c;
if (!user_guess || isNaN(user_guess)){
validation_alert();
} else {
if (guess.length === 4){
guess_string = user_guess.toString();
guess_array = guess_string.split('');
guess_array2 = guess_array;
for (i; i < 3; i++){
counter = i + 1;
c = counter;
for (c; c < 4; c++){
if (guess_array[i] == guess_array2[c]){
valid = false;
validation_alert();
return 11;
}
}
}
if (valid){
return 12;
} else {
validation_alert();
return 13;
}
} else {
validation_alert();
}
}
}
If you just need to check if the string has 4 unique number digits its much easier this way:
function isValid(str){
var unique={};
for(var i=0;i<str.length;i++){//for each character in the string
unique[str[i]]=true;//we add the character as a key in unique object(the =true doesnt really matter)
}
var chars=Object.keys(unique);//we get an array with the keys in the object(we get an array with the unique characters)
if(chars.length != 4) return false; //if the unique chracters are different than 4, its not valid so return false
chars.sort();//we order the array in lexicographical order
if(chars[0]>= '0' && chars[0] <='9' && chars[3]>= '0' && chars[3] <='9') return true;//if the first character and the last ones are digits, then the ones in the middle wil be digits as well because of the sort we made. If they are, return true
return false;//if they are not both digits, return false
}
console.log(isValid('1111'))//false
console.log(isValid('9230'))//true
console.log(isValid('1343'))//false
console.log(isValid('a412'))//false
console.log(isValid(''))//false

Categories