I am a very very beginner in Javascript and am trying to use only very basics. I am trying to only allow two certain words to be accepted into a variable prompt. If anything else other than the two allowed words are entered, I want to display a message saying only the two words are allowed, and to try again until it’s correct. This is the code I am working with so far. Everything is working well until the last section
console.log("Start of the program"); var letters = /^[a-zA-Z]*$/; var number= prompt ("Which number between 1 and 30 do you want to translate?"); while (number <1) { alert("Please type an integer number between 1 and 30"); var number= prompt ("Which number between 1 and 30 do you want to translate?"); } while (number >30) { alert("Please type an integer number between 1 and 30"); var number= prompt ("Which number between 1 and 30 do you want to translate?"); } while (letters.test(number)) { alert("Please use digits"); var number= prompt ("Which number between 1 and 30 do you want to translate?"); } if (number => 1 && number <= 30) { var lang= prompt ("Which language do you want to translate into, French or German?"); } while(lang != "French" != "German") { alert("Only French or German is allowed"); var lang= prompt ("Which language do you want to translate into, French or German?"); }
Even if I enter “French” or “German” I still receive the “Only French or German is allowed” alert continuously. If I change the “while (lang !=)” to an “if (lang !=)” I receive the alert once regardless of if French or German has been correctly used, and then the program continues. I also would like it to not be case sensitive (accept French, french, FRENCH etc.) in my result which uses this code currently
if (number == 1 && lang == "French") { alert("The translation is " +frenchNumbers[1]);
Any help would be much appreciated
Thanks, Brad
Advertisement
Answer
You’re missing && lang
here:
while(lang != "French" && lang != "German")
JavaScript (nor any other language I’m currently aware of) allows you to compare a variable to two different values like this, without using a boolean operator and then repeating the name of the variable.
Interestingly enough, lang != "French" != "German"
is valid syntax, but it doesn’t mean what you might think.
First lang != "French"
is evaluated to either true
or false
. Then what happens next is either:
true != "German"
or false != "German"
…and both of those are always true.