If user "cancels" prompt box then - javascript

I have tried adding a Do/While loop, then I tried a If statement but I can't seem to get this to work.
I am trying to determine if the user hasn't made three guesses, and hits cancel on the userGuess prompt .. it would then return a alert("You are a chicken");
//declare variables
var sportsArray = new Array("Football", "Basketball", "Rollerblading", "Hiking", "Biking", "Swimming");
var name = "";
var score = 0;
var loops = 0;
// prompts for user name, checks for input.
do {
name = prompt("Enter your first name", "");
}
while (name == "");
for (loops = 1;loops <=3; loops++) {
var sGuess = prompt("Enter a sport guess", "");
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
// concats the two parts into one string
var usableGuess = sFirstCap + sSecondLow;
// if user hits cancel on the sGuess prompt
if (sGuess == "") {
alert("You are a chicken");
}
// checks if usableGuess is contained in the arry or not.
if (sportsArray.indexOf(usableGuess) === -1) {
document.write("Sorry! Try again.<br />");
score = score -5;
}
else {
document.write("You are good, try again.<br />");
score = score + 5;
}
}
//depending on the user score, prompts one of three messages.
if (score < 0) {
document.write(name + ", you do not demonstrate ESP tendencies at this time.<br />");
} else if (score < 15) {
document.write(name + ", you are not bad.<br />");
} else {
document.write("<br/>" + name + ", you are a mind reader!<br />");
}

The prompt return s a null value where clicked on cancel, so your substring() method fails with an error(Uncaught TypeError: Cannot read property 'substr' of null).
You need to check it as soon as the prompt is called, then continue like
var sGuess = prompt("Enter a sport guess", "");
if (sGuess == "") {
alert("You are a chicken");
continue;
}

Update sGuess checking from:
if (sGuess == "") {
alert("You are a chicken");
}
to next one:
if (sGuess == null) {
alert("You are a chicken");
}
If user click cancel sGuess would be equal to null, to verify third user tries was ended with cancel pressing add checking for loops counter value (sGuess == null && loops == 3).

Just check the result to see if there was a value supplied:
name = prompt("Enter your first name", "");
// If no name value was received:
if(!name){
alert("Chicken!");
}

"prompt" is returning null if the user hits cancel. In this case all your substr and subsequent code will fail.
var sGuess = prompt("Enter a sport guess", "");
if(sGuess !== null) {
// uses substrings to ultimately capitalize the 1st letter, and make everything after it lowerCase.
var sFirstPart = sGuess.substr(0, 1);
var sFirstCap = sFirstPart.toUpperCase();
var sSecondPart = sGuess.substring(1, sGuess.length);
var sSecondLow = sSecondPart.toLowerCase();
// concats the two parts into one string
var usableGuess = sFirstCap + sSecondLow;
} else {
// if user hits cancel on the sGuess prompt
alert("You are a chicken");
}
...

I ended up going with the following and it does the job, in this particular case.
// if user hits cancel on the sGuess prompt
if (!sGuess && loops < 4) {
alert("You are a chicken");
}

Related

Do loop keeps on repeating

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.

Javascript: Alert message after loop ends

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!

Hit register for a 1d Battleship game. Using array to record previous user inputs, then cross-checking them with current input

I am a novice programmer. I have started teaching myself JavaScript. I made a rudimentary battleship game. Problem is that if the user enters the same location(if it's a hit) 3 times the battleship sinks. To avoid that I added an array "userchoices" to record user inputs and then cross-check by iterating through a for-loop. the for loop, in turn, contains an If statement that should alert the user if they have already fired at the location before. Problem is that the if statement gets executed each time.
Please review the code below and suggest corrections. Thank you.
var randomloc = Math.floor(Math.random() * 5);
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var userchoices = [];
var hits = 0;
var guesses = 0;
var issunk = false;
function battleship() {
while(issunk == false)
{
guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");
console.log("users input = " + guess);
if (guess == null)
break;
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number. No of guesses has been
incremented.")
}
else{
guesses++;
userchoices[guesses] = guess;
console.log("users choices = " + userchoices);
}
/* for(var i = 0; i <= guesses; i++)
{
if(userchoices[guesses] = guess)
console.log("you have already fired at this location");
} */
if (guess == location1 || guess == location2 || guess == location3){
alert("Enemy Battleship HIT");
hits = hits + 1;
if (hits == 3){
issunk = true;
alert("Enemy battleship sunk")
}
}
else{
alert("You Missed");
}
}
if (issunk){var stats = "you took " + guesses + " guesses to sink the battleship. You accuracy was " + (3/guesses);alert(stats);}
else{alert("You Failed!"); issunk = false;}
}
This is the part that is causing an error
for(var i = 0; i<=guesses; i++)
{
if (userchoices[guesses] = guess){
console.log("you have fired at this location already");
}}
The if statement should execute only when the user enters a grid number that he already has fire upon, no matter hit or miss.
You are accessing the array by the wrong index. Try userchoices[i] instead of userchoices[guesses]. Also equality comparison is performed using 2 equal signs ==:
for(var i = 0; i<=guesses; i++)
{
if (userchoices[i] == guess){
console.log("you have fired at this location already");
}
}
This can also be expressed as:
if (userchoices.includes(guess)){
console.log("you have fired at this location already");
}
Also guesses should be incremented after adding the first value:
else{
userchoices[guesses] = guess;
guesses++;
console.log("users choices = " + userchoices);
}
EDIT
There is a logic error here as you are checking the array for the element after inserting it into the array, perform the check in the else statement before inserting the element. Combining all of the above:
else if (userchoices.includes(guess)){
console.log("you have fired at this location already");
} else {
userchoices[guesses] = guess;
guesses++;
console.log("users choices = " + userchoices);
}
After much-needed help from Avin Kavish and bit of tinkering of my own, I can now present an answer to my own question for future viewers.
Edit: More like my final program
function battleship()
{
var guess; //Stores user's guess
var userchoices = []; //records user's guess until ship is sunk or user chickens out
var issunk = false; //status of ship
var hits = 0; //number of hits
var guesses = 0; //number of guesses
var randomloc = Math.floor(Math.random() * 5); //Random Number Generator
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
while(issunk == false)
{
guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");
console.log("users input = " + guess);
if(guess == null) // If users presses 'OK' without entering anything or the 'Cancel' this would break the loop.
break;
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number. No of guesses has been incremented.");
guesses++; //Gotta punish the player.
}
else if (userchoices.includes(guess) == false) /*instead of doing what i did yo u
can change this line to "else if (userchoices.includes(guess)) and then put the
following oprations in its else clause. */
{
guesses++;
userchoices[guesses] = guess;
console.log("User choices = " + userchoices);
if (guess == location1 || guess == location2 || guess == location3)
{
alert("Enemy Battleship HIT");
hits = hits + 1;
if (hits == 3)
{
issunk = true;
alert("Enemy battleship sunk");
}
}
else
{
alert("You Missed");
}
}
else
{
alert("you have already fired at this location.")
}
if (issunk) //writing issunk == true is overkill
{
var stats = "you took " + guesses + " guesses to sink the battleship. You
accuracy was " + (3/guesses);
alert(stats);
}
}
if(guess == null && issunk == false)
console.log("You failed"); //Humiliate the user for chickening out.
userchoices = []; //Empties the array so user can start over again without relaoding the page
issunk = false; //sets issunk to false for a new game
var randomloc = Math.floor(Math.random() * 5); //creates new random numbers for ship coordinates
}
2D 7X7 version coming soon. Will post here.

Javascript writing if statements to prompt user for input

var noun;
var verb;
var adverb;
var adjective;
var pronoun;
var questions = 5; //this number can adjust
var paragraph;
var noun = prompt("Type Noun");
if (isNaN(noun) == "True"){
questions -= 1;
verb = prompt("Type Verb");
}else{
alert("You entered a number, please enter a Noun.");
}
if (isNaN(verb) == "True"){
questions -= 1;
adverb = prompt("Type Adverb");
}else{
alert("You entered a number, please enter a Verb.");
}
if (isNaN(adverb) == "True"){
questions -= 1;
adjective = prompt("Type Adjective");
}else{
alert("You entered a number, please enter a Adverb.");
}
if (isNaN(pronoun) == "True"){
questions -= 1;
}else{
alert("You entered a number, please enter a Pronoun.");
}
So the main idea is to have the user input a word.
For some reason it marks the boolean false and goes directly into the else statement.....
This is because isNaN("some text") returns a boolean true/false -- and true == "True" returns false. Your statements should read:
if (isNaN(noun) === true) {
}
....

for loop getting skipped in javascript

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.");

Categories