I want to repeat the code until the user gets the no. right. How do I do this ?
This is the code:-
function getRandomNumber(min,max){
return Math.floor(Math.random()*(max - min + 1 ))+min;
}
randomNumber=(getRandomNumber(1,10));
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
console.log("not matched");
}
You could either use a while loop that calls a "break" statement once the user inputs the correct answer, or you could use a function like this:
function getInput(){
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
consol.log("not matched");
getInput(); //Gets the user's input again
}
}
Here you go...
Found needs to be set to false before you start, otherwise the function will only run one. There is little point having the function definition inside the while loop, since it will be created as a global variable.
var found = false;
function getRandomNumber(min,max) { return Math.floor(Math.random()*(max - min + 1 ))+min; }
while ( found != true ) {
var randomNumber = getRandomNumber(1,10);
console.log('Random Number is..',randomNumber);
var input = prompt("Please enter a no. between 1 and 10:","");
if ( input == randomNumber ) {
alert('Well Done')
found = true;
} else {
console.log("not matched");
}
}
Related
how to write simple if take the first expression. Example bellow, my code is looks like to much.
i mean first condition email.val() and second !validateEmail(email.val()) with or expression. my big question is how to detect that first or second condition is executed ?
if(email.val() == "" || !validateEmail(email.val())){
//call the condition again
if(email.val() ==""){
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}else{
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}
email.focus();
}
so I don't need to call this if again
if(email.val() == ""){
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}else{
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000)
}
Personally I do that way.
It allow in future to add other errors message or easy change them if needed.
// separate messages values to avoid long texts in the nested if part
// and prevent them from being searched for in parts of code
// where they can be scattered in several places, and possibly repeated
const errorMessage =
{ email_empty : '<p>Email Cant be empty</p>'
, email_wrong : '<p>Wrong email format</p>'
}
var messageError = ''
if(email.val()==='') { messageError = errorMessage.email_empty }
else if ( !validateEmail(email.val())) { messageError = errorMessage.email_wrong }
if (messageError) {
$("#error").html(messageError)
$("#error").show()
setTimeout(function(){$("#error").fadeOut();}, 2000)
email.focus()
}
You have roughly
if (condition1 || condition2) {
if (condition1) {
foo();
} else {
bar();
}
moo();
}
The else can only trigger when condition1==false and condition2==true, hence you can write the same as
if (condition1) {
foo();
moo();
} else if (condition2) {
bar();
moo();
}
So, as I see you're validating an email, there are two options you can look to avoid the nested if-else block or basically repeating your code again.
User Regex Expression: You can validate email, and check if it's empty as well.
if(!regexPat1.test(email)) {
// Do something
}
if(!regexPat2.test(email)) {
// Do something
}
Use nest condition : With this you can avoid rewriting same condition again.
if(email.val().trim() !=="") {
if(!validateEmail(email.val().trim()) {
//Throw invalid email error
}else {
// Do something
}
}else {
// Trow empty value error
}
There can be better solutions as well but I think this solves your doubt.
Simple rearrangement of your existing code.
if(email.val() == "") {
$("#error").html("<p>Email Cant be empty</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000);
email.focus();
} else if (!validateEmail(email.val()) {
$("#error").html("<p>Wrong email format</p>");
$("#error").show();
setTimeout(function(){$("#error").fadeOut();}, 2000);
email.focus();
}
I have this example code
var randFriend = friendList[Math.floor(Math.random() * friendList.length)];
if (randFriend == admin) {
//Here
}
else if (randFriend != admin) {
client.removeFriend(randFriend);
}
How can I do if if randfriend == admin to do again var randFriend = friendList[Math.floor(Math.random() * friendList.length)]; and check if(randFriend == admin) again. In other words, to restart that again.
I think that it's done with return, but I don't know. Thanks
I wouldn't use recursion or loops with random conditions, because you will have problems to estimate the runtime, and if the use case changes and you would have more elements you want to ignore, then the probability to find the correct element will decrease.
A better idea would be to filter the array to remove the elements you want to ignore and then pick a random element from that list.
var nonAdminList = friendList.filter(person => person != admin);
if( nonAdminList.length === 0 ) {
throw new Error('no non admin persons available');
}
client.removeFriend(nonAdminList[Math.floor(Math.random() * nonAdminList.length)]);
If I'm understanding the question correctly, you could use a while loop to keep randomizing until an admin isn't selected
var friendAdmin = true;
var randFriend;
while(friendAdmin){
randFriend = friendList[Math.floor(Math.random() * friendList.length)];
if(randFriend != admin) friendAdmin = false;
}
client.removeFriend(randFriend);
I would put your code into a function so that you can invoke the function again if you want to repeat it. For example:
function choose(){
var randFriend = friendList[Math.floor(Math.random() * friendList.length)];
if(randFriend == admin){
choose(); //this repeats the choose function, which will run the random friend code again
}
else if(randFriend != admin){
client.removeFriend(randFriend);
return; //this exits the function
}
}
I am trying to query the user twice (more than once in general), but everything gets printed out together and the first response get processed by both functions. I believe this has to do with the asynchronous nature of node.js. Can you please point me towards module that would take care of this for me or an implementation in prompt module? Thank you.
var prompt = require('prompt');
prompt.start();
console.log("Enter a number: ");
prompt.get(['number'], function(err, result) {
if (!isNaN(result.number)) {
console.log("You entered a number.");
} else {
console.log("You did not enter a number.");
}
});
var prompt2 = require('prompt');
prompt2.start();
console.log("Enter a number again: ");
prompt2.get(['number1', 'number2'], function(err, result) {
if (Number(result.number1) > Number(result.number2))
console.log("The first input is bigger");
else if (Number(result.number1) == Number(result.number2))
console.log("Both inputs are equal");
else
console.log("The second input is bigger");
});
I am not sure if you actually need both prompt instances. I think you can achieve what you want with only one prompt and just calling get second time within the first get's callback.
var prompt = require('prompt');
prompt.start();
console.log("Enter a number: ");
prompt.get(['number'], function(err, result) {
if (!isNaN(result.number)) {
console.log("You entered a number.");
} else {
console.log("You did not enter a number.");
}
console.log("Enter a number again: ");
prompt.get(['number'], function(err, result) {
if (result.number < 20)
console.log("small");
else if (result.number < 50)
console.log("medium");
else
console.log("large");
});
});
I am using jQuery Steps plugin (LINK HERE). Problem is in one IF statements that returns wizzard to first step (not on step that is currently indexed). All IF statements are working correctly expect this one. That if statemnt is checking if phone number is in correct format:
Here is code:
onFinishing: function (event, currentIndex) {
var filter = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!filter.test($("#email").val())) {
$("#emailError").text("e-mail is wrong");
return false;
}
if (!filter.test($("#email2").val())) {
$("#email2Error").text("e-mail is wrong");
return false;
}
var newnum = parseInt($("#numppl").val());
if(Math.floor(newnum) != newnum && !$.isNumeric(newnum)){
$("#numpplError").text("Number error");
return false;
}
if (!($("#numppl").val() >= 1 && $("#numppl").val()<=10)){
$("#numpplError").text("Number error");
return false;
}
if ($("#email").val()!=($("#email2").val())){
$("#email2Error").text("address don't match");
return false;
}
/*IF Statment bellow is bugged */
if ($("#phone").length) {
if(!$("#phone").match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/)){
$("#phoneError").text("Wrong format");
return false;
}
}
return true;
},
Make correction in IF Statement in which you commented as bug :
pval = $("#phone").val(); //Store the value of "Phone"
if (pval.length) { //Check for non empty
if(!pval.match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/)) { // Check format.
$("#phoneError").text("Wrong format");
return false;
}
}
$("#phone").length isn't same as the length of phone number
inspite of $("#phone").length use ($("#phone").val()).length
similarly inspite of $("#phone").match(regular Expression) use
($("#phone").val()).match(regular Expression)
I have this javascript and I get the error "function expected". I can't see anything wrong with my javascript. Please help. Thanks.
function checkrewardname()
{
var my=document.getElementById("Rname");
var con=my.value;
var mine=document.getElementById("forref").value.split('\n');
if (con == "")
{
alert("Enter a Reward Name.");
}
else
{
var i=0;
while(i<=mine.length)
{
if (mine(i) == con)//error here
{
alert("Duplicate reward. Please enter a new reward.");
}
else
{
document.getElementById("validate").click();
alert("The reward has been saved.");
}
i++;
}
}
}`
mine is an array but you are calling it as if it were a function. Use mine[i] rather than mine(i) and you'll access the array by index rather than generating an error. (Just a note; most C-style languages use [ and ] for array access and reserve ( and ) for function invocation).
You also have while(i<=mine.length)
shouldn't it be while(i < mine.length)