I'm new to js/programming and just making a simple calculator using prompt. I'm trying to validate that what's been entered are numbers and not strings. I tried this
var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();
switch (operatorType) {
case 'add':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
if (isNaN(i) === false) && (isNaN(j) === false) {
document.write(i+" plus "+j+" equals "+(i+j));
} else {
document.write("You didn't enter two numbers.");
}
break;
As well as if (i != 'string') && (j != 'string') but I keep getting "Unexpected token &&". I looked it up and if/else within a case is valid so I'm not sure what I'm doing wrong.
Full code if it helps
var operatorType = prompt("Do you want to add, subtract, multiply or divide?").toLowerCase();
switch (operatorType) {
case 'add':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
if (isNaN(i) === false) && (isNaN(j) === false) {
document.write(i+" plus "+j+" equals "+(i+j));
} else {
document.write("You didn't enter two numbers.");
}
break;
case 'subtract':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" minus "+j+" equals "+(i-j));
break;
case 'multiply':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" multiplied by "+j+" equals "+(i*j));
break;
case 'divide':
var i = prompt("Enter your first number");
var j = prompt("Enter your second number");
document.write(i+" divided by "+j+" equals "+(i/j));
break;
default:
document.write("Please enter whether you want to add, subtract, multiply or divide.");
break;
}
You have your parenthesis in the wrong spot causing the syntax error. You need to move the parenthesis in this line to change from:
if (isNaN(i) === false) && (isNaN(j) === false) {
So that it becomes:
if (isNaN(i) === false && (isNaN(j) === false)) {
You'll also need to convert the strings to numbers so that your code truly adds/etc instead of concatenates the text.
Related
In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();
I am facing a problem to create a loop which will loop back to the previous functions when the user does not want the program to stop (if the user wants it to stop, the program will continue with other functions).
I need to create a list of functions to do base conversion while showing the logic:
Step1: prompt for a number
Step2: prompt for an alphabet (b for Binary/o for Octal/h for Hexadecimal) as the base
Step3: convert it to a string (e.g. "108sup10 = 1101100sup2" & "63300268sup10 = 3C5E2A7sup16")
Step4: alert the string answer in a statement (e.g: Base 10 number 63300268 is 3C5E2A7 in Hexadecimal)
Step5: prompt to stop. If user's input is not "s", it will repeat step 1~4, else it continue to step 6.
Step 6: alert the max and min number entered from (repeated) step1's input.
for step 1,2,3,4,6, it is mandatory to use functions.
May I know how do I code for STEP5 in order to loop back from step 1-4 when stopping is prompted? Do I need a function for this?
//prompt to get number
function getNumber() {
var myNumber;
do {
myNumber = Number(prompt("Enter an unsigned base 10 number:")); //prompt user's input to be excecuted first
} while (myNumber < 0) //loop will run again and again as long as the number is less than zero
return myNumber;
}
//prompt to get base
function getBase() {
var myBase;
do {
myBase = (prompt("Enter b for binary, o for octal and h for hexadecimal"));
} while (!(myBase == "b" || myBase == "B" || myBase == "s" || myBase == "S"|| myBase == "h" || myBase == "H")) //loop if the input is not b, s or h
return myBase;
}
//converting the base to the number
function baseConversion(number, newBase) {
var arr = [];
if (newBase == "b" || newBase == "B") {
newBase = 2;
} else if (newBase == "o" || newBase == "O") {
newBase = 8;
}else if (newBase == "h" || newBase == "H") {
newBase = 16;
}
do { //putting the each remainder at the front of the array
arr.unshift(number%newBase);
number = Math.floor(number/newBase); //round down the divided answer
} while (number>newBase-1) //loop as long as this condition holds
arr.unshift(number);
return arr;
}
//function to string the arrays
function convertToString(number, base) {
var resultString = ""
for (var i = 0; i < results.length; i++) {
var digit = results[i];
if (digit > 9) {
switch (digit) {
case 10:
digit = 'A'
break;
case 11:
digit = 'B'
break;
case 12:
digit = 'C'
break;
case 13:
digit = 'D'
break;
case 14:
digit = 'E'
break;
case 15:
digit = 'F'
break;
}
}
resultString += digit;
}
return resultString
}
//function to alert the answer statement
function alertAnswer() {
var statement = alert("Base 10 number:" + myNumber + "is" + base + "in" + myBase);
return statement;
}
//function to find the maximum number in the array
function myMax(myArray) {
var max = myArray[0];
for (var z = 0; z < myArray.length; z++) {
if (myArray[z] > max) {
max = myArray[z];
}
}
return max;
}
//function to find the minimum number in the array
function myMin(myArray) {
var min = myArray[0];
for (var z = 0; z < myArray.length; z++) {
if (myArray[z] > min) {
min = myArray[z];
}
}
return min;
}
Sorry if I'm mistaken, but is this what you're looking for?
var promptVar = false;
do
{
//function calls for steps 1~4
prompt();
}
while (promptVar == false)
function prompt()
{
if (confirm('Do you want to continue to step 6?'))
{
promptVar = true;
} else {
promptVar = false;
}
}
I just started learning JavaScript and I'm fiddling around with some code and I can't seem to find a way to really add two variables up and calculate their sum. I'm declaring 3 variables where I set one variable to the answer and the 2 others as the two numbers. So basically a, b, c where c = (a + b). However, whenever I try to run the code the result ends up in 'ab' instead of 'a + b' so if a = 5 and b = 10 it says '510' instead of '15'.
All the other symbols like '-' , '/' and '*' are working as intended, the only one that is not working is the '+'.
I figure the computer thinks I'm trying to print out the two strings but I want to add them up instead, just like you do when you alert something for example: alert("Hello World" + a);
Am I thinking in the right direction or is the problem something else? Here's the source code:
function addTwoNumbers(firstNumber,secondNumber,numberAdded){
if(numberAdded == '+'){
numberAdded = (firstNumber + secondNumber);
alert("The summ of the two numbers is equal to: " + numberAdded);
}
else if(numberAdded == '-'){
numberAdded = (firstNumber - secondNumber);
alert("The difference of the two numbers is equal to: " + numberAdded);
}
else if(numberAdded == '/')
{
numberAdded = (firstNumber / secondNumber);
alert("The 'kvot' of the two numbers is equal to: " + numberAdded);
}
else if(numberAdded == '*'){
numberAdded = (firstNumber * secondNumber);
alert("The product of the two numbers is equal to: " + numberAdded);
}
else
{
alert("I told you to use '+, -, / and *' not anything else!");
}
}
var checker = true;
while(checker == true){
alert("You will now be prompted to enter two numbers.");
var firstNumber = prompt("Please enter the first number.");
var secondNumber = prompt("Please enter the second number.");
var numberAdded = prompt("Would you like to use '+, -, /, or * ?'");
checker = false;
addTwoNumbers(firstNumber, secondNumber, numberAdded);
if(numberAdded != '+' && numberAdded != '-' && numberAdded != '/' && numberAdded != '*'){
checker = true;
}
option = 0;
while(option != 'y' && option != 'n'){
var option = prompt("Would you like to make a calculation again? (y/n)");
if(option == 'y'){
checker = true;
}
else if(option == 'n'){
checker = false;
}
else{
alert("I said (y/n), try again...");
}
}
}
The prompt function return a string. So when you use the + operator on two string you are combining them together. Instead, parse the number strings to a number:
var firstNumber = parseInt(prompt("Please enter the first number."), 10);
var secondNumber = parseInt(prompt("Please enter the second number."), 10);
I'm trying to write this exercise from a book:
Write a program to ask yourself, using prompt, what the value of 2 + 2
is. If the answer is "4", use alert to say something praising. If it
is "3" or "5", say "Almost!". In other cases, say something mean.
I made this attempt:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input = 4)
print ("Awesome !");
else if (input = 3 || input = 5)
print ("Close !");
else if (input = 'number'
print ("wrong number");
else if (input = 'random text')
print ("use numbers only!")
I know it is wrong. This is I intended to do:
I need to determine the type of var, not just the value. I need to make var either number or string (according to typeof). Why ? For prompt imput, because below else if condition, will be based on which type was inputted.
I know that exercise didn't asked it, but I want make it superior.
= is assignment. == is comparison.
To convert the string that prompt gives you to a number, use parseInt(input,10) - that said, JavaScript will typecast for you, so there's no real need here. You can even tell if the user entered something that isn't a number by testing isNaN(input) for your "use numbers only" result.
So something like this:
var input = parseInt(prompt("How much is 2 + 2?",""),10);
if( input == 4) alert("Awesome!");
else if( input == 3 || input == 5) alert("Almost!");
else if( input == 10) alert("No GLaDOS, we're working in Base 10 here.");
else if( input == 42) alert("That may be the answer to Life, the Universe and Everything, but it's still wrong.");
else if( isNaN(input)) alert("Use numbers only please!");
else alert("You are wrong!");
I'd personally suggest:
var guess = parseInt(prompt('What is 2 + 2?'), 10);
switch (guess) {
case 4:
console.log('Well done!');
break;
case 3:
case 5:
console.log('Almost!');
break;
default:
console.log('Seriously? No.');
break;
}
JS Fiddle demo.
Or, to be more functional about it:
function answerMath (sum) {
var actual = eval(sum),
guess = parseInt(prompt('What is ' + sum + '?'),10);
if (guess === actual) {
console.log('Well done!');
}
else if (guess + 1 === actual || guess - 1 === actual) {
console.log('Almost!');
}
else {
console.log('Seriously? No.');
}
}
answerMath ('2*3');
JS Fiddle demo.
Note that while eval() is the only means I could think of in this situation to evaluate the sum passed to the function as a string, I'm not entirely sure it's a good recommendation (albeit eval() has more bad press than it perhaps deserves, though it does present risks).
In most programming languages, = is assignment, and == tests for equality. So
a = 4 assigns the number 4 to the variable a. But a == 4 checks to see if a is equal to 4.
So for your code, you'd need:
var input = "" || 'number'
prompt ("How many is 2+2 ?", input)
if (input == 4)
print ("Awesome !");
else if (input == 3 || input == 5)
print ("Close !");
else if (input == 'number')
print ("wrong number");
else if (input == 'random text')
print ("use numbers only!")
I'm going to build on David Thomas's answer a little, because if you wanted to make it better, you could easily turn it into a little game.
var numa = Math.round(Math.random() * (100 - 1) + 1);
var numb = Math.round(Math.random() * (100 - 1) + 1);
var answer = numa + numb;
var guess = parseInt(prompt('What is ' + numa + ' + ' + numb + '?'), 10);
switch (guess) {
case answer:
alert('Well done!');
break;
case (answer - 1):
case (answer + 1):
alert('Almost!');
break;
default:
alert('Seriously? No.');
break;
}
Further things you could do would be to include a timer to see how long the user took to answer the question, and ask them if they way to play again when they get it right.
Here is a Fiddle: http://jsfiddle.net/6U6eN/
This question already has answers here:
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 1 year ago.
Pretty straight-forward what I want to do:
If the input is 0, it means that they didn't input a number and it
should tell you so.
When the input is 7, it should say that you got it right.
Anything else, it should tell you that you got it wrong.
But it just outputs the "7 is correct" line no matter what the input is, and I can't figure it out what is wrong.
<script type="text/javascript">
function problem2 ()
{
var number = 0;
var text=document.getElementById("output");
number = prompt("Enter a number between 1 and 10 please" , 0);
if (number = 0)
{
text.value = "You didn't enter a number!";
}
if (number = 7)
{
text.value = "7 is correct!";
}
else
{
text.value = "Sorry, ", input, "is not correct!";
}
}
</script>
<input type="button" value="Click here" onclick="problem2()">
<input id="output" type="text">
You're assigning with =. Use == or ===.
if( 0 == number ){
text.value = "You didn't enter a number!";
}
Also, be wary of your brace placement. Javascript likes to automatically add semicolons to the end of lines. Source.
You are using assignment operators as your conditionals instead of comparison operators:
if (number = 0) // falsy. Same as if (false)
{
text.value = "You didn't enter a number!";
}
if (number = 7) // truthy. Same as if (true)
{
text.value = "7 is correct!";
}
else
{
text.value = "Sorry, ", input, "is not correct!";
}
Alternatively you can use a switch and organize the conditionals a bit easier:
switch (number) {
case 0:
text.value = "You didn't enter a number!";
break;
case 7:
text.value = "7 is correct!";
break;
default:
text.value = "Sorry, ", input, "is not correct!";
break;
}
Here is a code with the some fixes and improvements (I commented what I changed):
function problem2 (){
//I multiplied by * 1 to work with numbers, also used || to default to 0 in case of NaN
var num = (prompt("Enter a number between 1 and 10 please" , 0) * 1) || 0;
var msg = "";
if (!num){ //I prefer this over 'num == 0'
msg = "You didn't enter a number!";
//you should use 'else if' in this case
}else if (num == 7){//'=' is for assignment, use '==' or '===' instead
msg = "7 is correct!";
}else{
//you had an undefined var 'input', you probably meant 'num'
//you also were connecting var and strings using commas, use '+' instead
msg = "Sorry, " + num + " is not correct!"; //added a space in ' is'
}
//no need to store the element in a var anymore :D
document.getElementById("output").value = msg;
}
Aditionally, two more changes can be made:
only one var (e.g var something = "", somethingElse = 99;)
assign the default text from the beginning, like var msg = "default" and remove the else
Note: an undocumented change I made was to rename some vars, I encourage everyone to stop using vars like number, text, string, if you have this bad habit, you will eventually use illegal var names by mistake.