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) {
}
....
Related
The user has 3 attempts to enter the correct password. I noticed that if the password is entered correctly on the second attempt, the password prompt would still pop up and ask them to re-enter the password. What do I do so that as soon as the correct password is entered, the prompt will no longer pop up?
var correctAnswer = 'mypassword';
var counter = 3;
var guess = prompt('what is your password?');
if (guess !== correctAnswer) {
while (counter -= 1) {
counter > 3;
console.log(`Please re-enter your password. You have ${counter} more attemps.`);
var guess = prompt('what is your password?');
}
} else {
console.log('Password is correct')
}
Here is a clearer solution:
var correctAnswer = 'mypassword';
var counter = 3;
var guess;
while(counter--) {
guess = prompt('what is your password?');
if(guess === correctAnswer) {
console.log('Password is correct');
break;
} else if(counter > 0) {
console.log(`Please re-enter your password. You have ${counter} more attemps.`);
}
}
how to tell javascript that the user enter a string in the prompt box and work with it in an if statment ? If the user enters a string of letters I want it to alert "You did not enter a number", and if they entered a string if digits then continue with the logic.
var userGess = prompt("guess a number");
var secretNumber = 7;
if (Number(userGess) > secretNumber) {
alert("the number is to high")
} else if (Number(userGess) < secretNumber) {
alert("the number is to low")
} else if (Number(userGess) == secretNumber) {
alert("you are correct")
} else if (userGess == toString(userGess)) {
alert("you didnt type a number")
}
You can use isNaN(userGess) to check if a given string userGess is non-numeric.
However, that returns false if userGess is empty string, so you have to explicitly check it. So your final condition becomes
userGess === "" || isNaN(userGess)
var userGess = prompt("guess a number");
var secretNumber = 7;
if(userGess === "" || isNaN(userGess)) {
alert("You didn't enter a number")
} else if (Number(userGess) > secretNumber) {
alert("the number is to high")
} else if (Number(userGess) < secretNumber) {
alert("the number is to low")
} else if (Number(userGess) == secretNumber) {
alert("you are correct")
}
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.
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");
}
I have been trying for days to get this to work. I have the basic code but every time I try to get the last requirement added, I break the code. I'm sure I am missing a lot and that's why I can't add the alert box with the count of displays. So it asks the users name, the number of times they want to see and alert box and if they enter invalid answers they see alert boxes telling them to enter a correct value. The last part that I am stuck on is the value the user enters determines how many alert boxes show their name and the box needs to say which box it is. So, <Name> this is time number <count of displays> of <total time to display>. I was trying different things with limiting and FOR , with the user Y variable being the limiter. Any clues or help would be greatly appreciated.
<!DOCTYPE html>
<html>
<body>
<p>Please enter your name followed by how many times you would like to be alerted.</p>
<button onclick="myFunction()">Start</button>
<script>
function myFunction() {
var x;
var name = prompt("Please enter your name", "");
if (name == null || name == "") {
alert("Please input a name.");
return false;
}
else {
var y;
var y = prompt("Please enter a number between 1-10");
if (y == null || y == "") {
alert("Please input a number for the times to alert the name.");
return false;
}
if (y > 10) {
alert("Please input a number between 1 and 10.")
var y = prompt("Please enter a number between 1-10");
}
if (y <= 0) {
alert("Please input a number great than zero.")
var y = prompt("Please enter a number between 1-10");
}
}
}
</script>
</body>
</html>
This gets rid of most of your alert statements and keeps prompt'ing until a valid value is submitted.
function myFunction() {
var x,y,name = "";
while(name.length < 1) {
name = prompt("Please enter your name", "");
}
while(!((y > 0) && (y <11))) {
y = prompt("Please enter a number between 1-10");
}
for(x = 0; x < y; x++) {
alert(name);
}
}
Working example:
http://jsfiddle.net/DwxmT/
Not much to change.
Try:
function myFunction() {
var x, y;
var name = prompt("Please enter your name", "");
if (name == null || name == "") {
alert("Please input a name.");
return false;
}
else {
var y = prompt("Please enter a number between 1-10");
if (y == null || y == "") {
alert("Please input a number for the times to alert the name.");
return false;
}
while (y >= 10 || y <= 0) {
alert("Please input a number between 1 and 10.")
var y = prompt("Please enter a number between 1-10");
if (y == null || y == "") {
alert("Please input a number for the times to alert the name.");
return false;
}
}
}
for(var i = 0; i < y; i++) {
alert("this is an alert");
}
}
This checks for 1 <= y <= 10 in a loop.
See http://jsfiddle.net/tMXNM/2/