Java Reference
In-Depth Information
exercise 2 Question
The following code uses the prompt() function to get two numbers from the user. It then adds those
two numbers and writes the result to the page:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Question 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number","");
var secondNumber = prompt("Enter the second number","");
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber +
" equals " + theTotal);
</script>
</body>
</html>
However, if you try out the code, you'll discover that it doesn't work. Why not? Change the code so
that it does work.
exercise 2 Solution
The data that the prompt() actually obtains is a string. So both firstNumber and secondNumber
contain text that happens to be number characters. When you use the + symbol to add the two
variables together, JavaScript assumes that because it's string data, you must want to concatenate
the two and not sum them.
To make it explicit to JavaScript that you want to add the numbers, you need to convert the data to
numbers using the parseFloat() function:
var firstNumber = parseFloat(prompt("Enter the first number",""));
var secondNumber = parseFloat(prompt("Enter the second number",""));
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber + " equals " +
theTotal);
Save this as ch2 _ question2.html .
Now the data returned by the prompt() function is converted to a floating‐point number before
being stored in the firstNumber and secondNumber variables. Then, when you do the addition that
is stored in theTotal , JavaScript makes the correct assumption that, because both the variables are
numbers, you must mean to add them up and not concatenate them.
The general rule is that where you have expressions with only numerical data, the + operator means
“do addition.” If there is any string data, the + means concatenate.
Search WWH ::




Custom Search