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 together and writes the result to the page:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<script language=”JavaScript” type=”text/javascript”>
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 the code out, 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 we use the + symbol to add the two variables
together, JavaScript assumes that since it's string data, we must want to concatenate the two together
and not sum them.
To make it explicit to JavaScript that we want to add the numbers together, we 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_q2.htm.
Now the data returned by the prompt() function is converted to a fl oating-point number before being
stored in the firstNumber and secondNumber variables. Then, when we do the addition that is stored
in theTotal, JavaScript makes the correct assumption that, because both the variables are numbers, we
must mean to add them up and not concatenate them.
The general rule is that where we have expressions with only numerical data, the + operator means “do
addition.” If there is any string data, the + will mean concatenate.
Search WWH ::

Custom Search