Sentinel program isn't working - javascript

I'm a beginner, and I need some help with my assignment. I can't work out what I've done wrong.
I have to make a program to read a collection of exam scores ranging in value from 0 to 100 and -1 to stop processing. Input and validate the score. The program should count and print the number of passes (>=50) and the number of fails (0-50). When a score of -1 is entered, the number of passes and the number of fails are displayed.
<script>
var score = 0;
var passCount = 0;
var failCount = 0;
score = parseInt(prompt("Input score between 1-100, -1 to quit","0"));
while (score !< 0){
if (score >= 50 || score <= 100){
passCount = passCount + 1;
alert ("You passed! Pass count = "+passCount+"Fail count = "+failCount);
}
else
if (score<50){
failCount = failCount + 1;
alert ("You failed! Pass count = "+passCount+"Fail count = "+failCount);
}
else
if (score > 100){
alert ("Invalid number");
}
score = parseInt(prompt("Input score between 1-100, -1 to quit","0"));
}
document.write ("Total: Passes - "+passCount+"Fails "+failCount);
</script>

Changes to be done:
while (score >= 0)
There is no operator !<. You either have to use while (! (score<0)) or while (score >=0) or while (score != -1)
if (score >= 50 && score <= 100)
Since you are using || OR operator in original code, the control never goes to the failCount branch. Need to use AND operator for the condition to be valid.
Final code:
<script>
var score = 0;
var passCount = 0;
var failCount = 0;
score = parseInt(prompt("Input score between 1-100, -1 to quit","0"));
while (score >= 0){
if (score >= 50 && score <= 100){
passCount = passCount + 1;
alert ("You passed! Pass count = "+passCount+"Fail count = "+failCount);
}
else
if (score<50){
failCount = failCount + 1;
alert ("You failed! Pass count = "+passCount+"Fail count = "+failCount);
}
else
if (score > 100){
alert ("Invalid number");
}
score = parseInt(prompt("Input score between 1-100, -1 to quit","0"));
}
document.write ("Total: Passes - "+passCount+"Fails "+failCount);
</script>

try to change your condition while(score != -1)

Related

Howcome when I run my code, does it infinitely repeat the same statement?

I am writing code to make a guessing game with parameters as follows: Guessing Game Prompt. Could someone please help me figure out why when I run it, it constantly outputs the same two lines infinitely and doesn't give me an opportunity to guess again? Below is the code that I have written.
var randNum = Math.random() * (50 - 0) + 0;
var userGuess = prompt ("Choose a number between 1 and 50: ");
var count = 0;
var controlNum = 0;
while (userGuess != randNum){
if (userGuess == randNum) {
controlNum = 1
console.log ("YOU GOT IT!");
console.log (count);
} else if (userGuess > randNum) {
console.log ("TOO HIGH");
console.log ("Try Agian");
count ++
} else if (userGuess < randNum) {
console.log ("TOO LOW");
console.log ("Try Again");
count ++
}
}
Thank you for your help!
You have the prompt to choose a number outside of your while loop.
Therefore, userGuess never actually changes, and it keeps comparing userGuess to randNum. That's an infinite loop (unless you get it right the first time).
Try this:
var randNum = Math.random() * (50 - 0) + 0;
var userGuess = 0;
var count = 0;
var controlNum = 0;
while (userGuess != randNum){
userGuess = prompt ("Choose a number between 1 and 50: ");
if (userGuess == randNum) {
controlNum = 1
console.log ("YOU GOT IT!");
console.log (count);
} else if (userGuess > randNum) {
console.log ("TOO HIGH");
console.log ("Try Agian");
count ++
} else if (userGuess < randNum) {
console.log ("TOO LOW");
console.log ("Try Again");
count ++
}
}
First of all, Math.random will give you number in floating-point pseudo-random number in the range 0 to less than 1. So you need to get the int part only.
Second You need to ask the user to guess again so you need to prompt again after checking all condition
var randNum = Math.floor(Math.random() * (50 - 0) + 0);
var userGuess = prompt("Choose a number between 1 and 50: ");
var count = 0;
var controlNum = 0;
while (userGuess != randNum) {
if (userGuess == randNum) {
controlNum = 1;
console.log("YOU GOT IT!");
console.log(count);
} else if (userGuess > randNum) {
console.log("TOO HIGH");
console.log("Try Agian");
count++;
} else if (userGuess < randNum) {
console.log("TOO LOW");
console.log("Try Again");
count++;
}
userGuess = prompt("Choose a number between 1 and 50: ");
}

How to write a while loop inside an if-else loop

Please tell me what is wrong with my code. It seems like after continue; it still loops over the same block even if I use the largest number as an input. Here it still wants me to input a larger number:
// 1) Generate a random integer from 0 to 10 (reference: Math.random())
const RanNum = Math.floor(Math.random() * Math.floor(11))
console.log(RanNum)
// 2) Ask the user input (reference: prompt())
let userInput = prompt(`Give me a number`)
const userInputInt = parseInt(userInput)
console.log(userInput)
console.log(typeof(userInput))
console.log(userInputInt)
console.log(typeof(userInputInt))
if(isNaN(userInput)){
prompt(`Give me a freaking number`)
}else{
let x = 0;
while (x < 4) {
console.log('hi')
console.log(userInputInt)
console.log(RanNum)
if (userInputInt == RanNum) {
console.log(`win`)
prompt('YOU GOT IT MAN')
break;
}
else if (userInputInt < RanNum) {
x = x+1 ;
prompt('Larger please')
continue;
}
else if (userInputInt > RanNum) {
x= x+1
prompt('Smaller please')
continue;
}
}
if(x > 3){alert('More than 3 times')}
}
However, this one works fine. Can someone point to me what's wrong?
// Guess the number
const randomNumber = Math.floor(Math.random() * 11);
let trials = 0;
while(trials < 4){
const guess= parseInt(prompt("Give me a number(0-10)!"));
if(isNaN(guess)){
alert("You are not inputing a number");
// Works for while-loop, for-loop, do-while loop
continue;
}
trials++;
if(guess === randomNumber){
// Equal
alert("You win!!");
// If the player wins, terminate the game
// Works for while-loop, for-loop, do-while loop
break;
}else{
// Unequal
if(guess > randomNumber){
alert("Too large!");
}else{
alert("Too small");
}
}
}
if(trials > 3){
alert("You loses");
}
You can use switch-case except if-else:
let i = 0,
solution = Math.floor(Math.random() * Math.floor(11)),
max_tries = 3;
while (nmb !== solution && i < max_tries + 1) {
if (i < max_tries) {
var nmb = Number(prompt("Put number (1 - 10): "));
switch(true) {
case nmb > solution : console.log("Smaller please"); break;
case nmb < solution : console.log("Largest please"); break;
default : console.log("YOU GOT IT MAN");
}
}
else { console.log("You lose! Number was: " + solution) }
i++
}
You only need to add outputs to the console as in your variant.

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!

Why won't this javascript hot/cold app run?

added a while loop, and trying to end the loop by entering finish inside the loop. The game is still running after it the game is completed.
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
var correct = false;
while (!correct) {
correct = guessFunction();
var finish = false;
}
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!' + 'That was a total of ' + guessCount + ' guesses.');
correctGuess = true;
finish = true;
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
if (diff >= 1 && diff <= 10 && !correctGuess) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20 && !correctGuess){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30 && !correctGuess){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50 && !correctGuess){
alert('Cold');
guessFunction();
}
else if (diff > 50 && !correctGuess){
alert('Ice Cold');
guessFunction();
}
}
guessFunction();
Trying to get this code to run but it only allows for 2 alert windows when guessing the random number. Im not sure how to get this to run, perhaps the guessFunction is not running?
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!');
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
}
guessFunction();
if (diff >= 1 && diff <= 10) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50){
alert('Cold');
guessFunction();
}
else if ( diff > 50){
alert('Ice Cold');
guessFunction();
}
The script stops executing because you only call your function twice. If you want this to run until the user guesses the right number, you probably want a while loop:
var correct = false;
while (!correct) {
// guessFunction could return true if they get it right
correct = guessFunction();
}
Yes, your script is only executing twice before exiting. You've got your nesting wrong:
var number = Math.floor(Math.random() * 100) + 1; // generate random #
var guess;
var guessCount = 0;
var correctGuess = false;
var diff;
function guessFunction(){
guess = prompt('I am thinking of a number between 1 and 100. What is it?');
guessCount += 1;
var guessInt = parseInt(guess); //turn guesses into interger
if (guess == number){ //which number is bigger, guess or number
alert('Correct!');
correctGuess = true;
}
else if (guessInt > number) {
diff = guessInt - number;
}
else if (guessInt < number) {
diff = number - guessInt;
}
if (diff >= 1 && diff <= 10 && !correctGuess) {
alert('Very Hot');
guessFunction();
}
else if (diff < 10 && diff <= 20 && !correctGuess){
alert('Hot');
guessFunction();
}
else if (diff < 20 && diff <= 30 && !correctGuess){
alert('Warm');
guessFunction();
}
else if (diff < 30 && diff <= 50 && !correctGuess){
alert('Cold');
guessFunction();
}
else if (diff > 50 && !correctGuess){
alert('Ice Cold');
guessFunction();
}
}
guessFunction();
EDIT:
My answer is more verbose than it needs to be so that it relates directly to your question. The next step for you is to implement the better solution of a while loop mentioned in Menello's answer in your script.

Guess a number game, score counter giving incorrect result

I am making a simple 1 - 10 guess the number game with Javascript.
It can be viewed here Guessing game
To add up score i have a var score = 4 which de-increments each time the number guessed (with a for loop which is smaller than 5) incorrect. I += to var tally and display tally as score.
My problem is score always equals 0, and therefore does not add anything to tally, I am struggling to find a solution.
My javascript is:
var tally;
function play() {
var compNum = (Math.random() * 10).toFixed(0);
var score = 4;
for (var i = 0; i < 4; i++) {
if (i == 0) {
var userNum = prompt("Enter a number between 1 and 10");
} else {
if (userNum < compNum) {
userNum = prompt("Guess higher, you have " + (4 - i) + " turns left ", userNum);
} else if (userNum > compNum) {
userNum = prompt("Guess lower you have " + (4 - i) + " turns left ", userNum);
}
}
score--;
}
tally += score;
$("#score").html("score: " + tally);
if (i >= 3 && userNum != compNum) {
var again = confirm("Sorry you lost. The number was: " + compNum + " Play again?");
} else if (userNum == compNum) {
again = confirm("Well done! play again?");
i <= 5;
}
if (again) {
play();
}
if (userNum == "") {
i <= 5;
}
}
HTML:
<button onclick="play()">PLAY</button>
<div id="score"></div>
Your help is really appreciated
You should check whether the number entered by the use is equal to the random one and if that is the case exit form the for loop.
With your code the loop runs the whole 4 times,
In your loop, you need to check if the user has the right answer and exit the loop if they do.
for (var i = 0; i < 4; i++) {
if (i == 0) {
var userNum = +prompt("Enter a number between 1 and 10");
} else {
if (userNum < compNum) {
userNum = prompt("Guess higher, you have " + (4 - i) + " turns left ", userNum);
} else if (userNum > compNum) {
userNum = prompt("Guess lower you have " + (4 - i) + " turns left ", userNum);
}
}
if (userNum === compNum) {
// they guessed right, so exit the loop
break;
}
score--;
}
In addition, I'd check to see if isNaN(userNum) to check your user actually entered a number. It's up to you if you want to give them another chance if they don't.

Categories