I make a condition with Else-If to print a line like [You got A+, You got D]. Now I want to store one valid output line in a variable outside the condition.
var gradeMark = Math.round(totalNumber / 6);
//Generate grade mark
if (gradeMark >= 80) {
console.log("You got A+");
} else if (gradeMark >= 70) {
console.log("You got A");
}....
.....
else if (gradeMark >= 0) {
console.log("You got F");
} else {
console.log("It's not valid mark");
}
//Getting grading mark
var validGradeMark =
You can use defining variable instead of console log and it is out of condition now.
let gradeMark = Math.round(totalNumber / 6);
let validGradeMark;
// Generate grade mark
if (gradeMark >= 80) {
validGradeMark = "You got A+";
} else if (gradeMark >= 70) {
validGradeMark = "You got A";
}....
.....
else if (gradeMark >= 0) {
validGradeMark = "You got F";
} else {
validGradeMark = "It's not valid mark";
}
// Getting grading mark
console.log(validGradeMark);
Related
So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();
So my alternative version of this code is in Java, the logic is fairly similar although in JavaScript the userinput is repeated infinitely rather than carrying until the user loses. This is my working Java code for reference:
int stop =0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
do {
int card;
int upcommingcard;
String userinput;
card= rand.nextInt(13)+1;
System.out.println("Card is "+card);
System.out.println("Higher or Lower?");
userinput = scan.next();
upcommingcard = rand.nextInt(13)+1;
if(!userinput.equalsIgnoreCase("H")&&(!userinput.equalsIgnoreCase("L"))){
System.out.println("Invalid Input ");
}
else if((userinput.equalsIgnoreCase("H")) && (upcommingcard > card)){
System.out.println("Correct!");
}
else if(userinput.equalsIgnoreCase("L") && upcommingcard < card){
System.out.println("Correct!l ");
}
else {
System.out.println("You lost it was " + upcommingcard);
stop=1;
}
}while (stop != 1);
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JavaScript - Not working
var max=13;
var min=1;
var stop=0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is "+card+"... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do{
if((userinput !="H")&&(userinput !="L")){
console.log("Invalid input");
}
else if((userinput ="H")&&(upcommingcard > card)){
console.log("Correct!");
}
else if((userinput ="L")&&(upcommingcard < card)){
console.log("Correct!");
}
else{
console.log("You lost, it was "+ upcommingcard);
stop=1;
}
}
while(stop !=1);
Just to mention also that it registers that the user's input is correct although it fails to continue and just keeps on spitting out the same output until the browser crashes.
EDIT: Thanks for the responses! the loop works perfectly now, my only issue is that the logic is a bit flawed since sometimes I Input 'L' for 8 and upcoming int is 10.. Dispite this I get the Incorrect response.
It's not that your console isn't updating, it's that you never exit your loop if the input is incorrect, and you never offer them the option to try again.
Thus if they are incorrect, the loop will never end, the console won't be updated, and they can't retry.
I would recommend changing the code to the following, to alert the user to try again.
var max = 13;
var min = 1;
var stop = 0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do {
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input!");
userinput = prompt("Card is " + card + "... Higher or lower?");
} else if ((userinput == "H") && (upcommingcard > card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
There are some points I want to make on this:
Your Java and Javascript code logic differs. You had the variables and input reads inside do while in Java but outside in Javascript.
As your prompt right now is outside the loop, it will keep having the same input value everytime and not asking for another one, and will carry on until it's a wrong guess, or forever if it's an invalid input. And the next point worsens your problem:
Your if comparison operators are invalid. What you did, as mentioned in the comments, is a data assignment to userinput and will always return correct
That being said, I corrected it below while adding alert popups instead of console.log only:
var stop = 0;
do {
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input");
stop = 1; //Currently stopping if having invalid input, you can remove this later
} else if ((userinput == "H") && (upcommingcard > card)) {
//Note the '==' above, and also the next one for comparing equal values
console.log("Correct!");
alert("Correct");
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
Now, do compare the JS snippet above with your working Java code you've posted. If you compare again with your JS code, you should be able see what I meant by having different logic.
This is a simple login excercise for school. It is meant to give you 3 attempts to log in. I would like to make it so after the loop stops (the three attempts were used), it alerts the user that he has no remaining attempts and his account will be blocked.
Something like:
alert("You don't have any attempts left. Your account is now blocked);
Here is the loop I made:
var tries;
for (tries = 2; tries !== -1; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
Thanks in advance.
You where very close. I think this is what you want.
var tries;
for (tries = 2; tries >= 0; tries--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if (tries == 0) {
alert("You don't have any attempts left. Your account is now blocked");
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
}
You can achieve this recursively. Just decrease the number of Tries everytime wrong username or password is entered.
var TRIES = 3;
function ask() {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
return alert("Welcome.");
}
if (TRIES > 0) {
alert("Incorrect username and/or password. You have " + TRIES + " attempt(s) left.");
TRIES -= 1;
ask()
} else {
alert("You don't have any attempts left. Your account is now blocked");
}
}
ask()
var tries;
for (tries = 0; tries < 3; tries++) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else {
alert("Incorrect username and/or password. You have " + tries + " attempt(s) left.");
}
if(tries == 2)
{
alert("You don't have any attempts left. Your account is now blocked);
}
}
Perhaps you could achieve this by doing the following:
for (var attemptsRemaining = 3; attemptsRemaining > 0; attemptsRemaining--) {
let User = prompt("Enter your username:");
let Pass = prompt("Enter your password:");
if (User === "hello" && Pass === "world") {
alert("Welcome.");
break;
} else if(attemptsRemaining <= 1) {
alert("To many failed attempts. Your account is now blocked.");
}
else {
alert("Incorrect username and/or password. You have " + (attemptsRemaining - 1) + " attempt(s) left.");
}
}
}
The idea here is to add an additional check to see if the number of attemptsRemaining has reached one (or less, for robustness) at which point all attempts are expired. In this case, you display a popup to alert notifying the user that their account is now blocked.
Hope that helps!
I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");
this is my first question on stack overflow, I have only been coding for a few months and I know I am probably just missing something simple here. I am trying to create a simple program for learning purposes, computer auto picks number between 1-100, user then picks number and is alerted if their choice is hot or cold in relation to the computer number.
I am trying to pass the users answer from a form field into a JavaScript variable, then run the function to test their answer when a button is clicked. I am using jQuery for both of these.
Here is the application live: http://keithlamar.github.io/HotOrCold/
Here is my HTML:
<form>
Your Number <input id="guess" type="number" name="yournumber"><br>
</form>
<p id="pick">Click Here</p>
Here is my JavaScript:
var userNum = $('#guess').val();
var comNum = Math.floor(Math.random()*101);
var difference = function (a,b) {return Math.abs(a - b)};
var askNumber = function(){
if(userNum == comNum){
alert("You got it! You Win!")
}
else if(difference(userNum,comNum) < 5){
alert("Very Hot!");
}
else if(difference(userNum,comNum) < 10){
alert("Hot!");
}
else if(difference(userNum,comNum) < 20){
alert("Warm!");
}
else if(difference(userNum,comNum) > 20){
alert("Very Cold!")
}
else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function(){
$('#pick').click(function(){
askNumber();
});
});
It seems like the var userNum is not getting a value from the input. I think it may have something to do with nesting of functions within functions, but I am not entirely sure!
Thanks for any input!!
You need to read the values inside the function - in your code you are reading the input field during the page load(before the click happens)
function difference(a, b) {
return Math.abs(a - b)
};
function askNumber() {
//read the user input in the click handler
var userNum = parseInt($('#guess').val(), 10);
var comNum = Math.floor(Math.random() * 101);
//calculate the difference only once then reuse it
var diff = difference(userNum, comNum);
if (diff == 0) {
alert("You got it! You Win!")
} else if (diff < 5) {
alert("Very Hot!");
} else if (diff < 10) {
alert("Hot!");
} else if (diff < 20) {
alert("Warm!");
} else if (diff > 20) {
alert("Very Cold!")
} else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function () {
$('#pick').click(function () {
askNumber();
});
});
Demo: Fiddle