Java Reference
In-Depth Information
Here is an example of how an expression is evaluated:
3 + 4 * 4 + 5 * ( 4 + 3 ) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 - 1
(2) multiplication
3 + 16 + 5 * 7 - 1
(3) multiplication
3 + 16 + 35 - 1
(4) addition
19 + 35 - 1
(5) addition
54 - 1
(6) subtraction
53
Listing 2.6 gives a program that converts a Fahrenheit degree to Celsius using the formula
celsius
= ( 9 ) (fahrenheit
-
32).
L ISTING 2.6
FahrenheitToCelsius.java
1 import java.util.Scanner;
2
3 public class FahrenheitToCelsius {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6
7 System.out.print( "Enter a degree in Fahrenheit: " );
8
double fahrenheit = input.nextDouble();
9
10 // Convert Fahrenheit to Celsius
11 double celsius = ( 5.0 / 9 ) * (fahrenheit - 32 );
12 System.out.println( "Fahrenheit " + fahrenheit + " is " +
13 celsius + " in Celsius" );
14 }
15 }
divide
Enter a degree in Fahrenheit: 100
Fahrenheit 100.0 is 37.77777777777778 in Celsius
line#
fahrenheit
celsius
8
100
11
37.77777777777778
Be careful when applying division. Division of two integers yields an integer in Java. 9 is
translated to 5.0 / 9 instead of 5 / 9 in line 11, because 5 / 9 yields 0 in Java.
integer vs. floating-point
division
2.22
How would you write the following arithmetic expression in Java?
Check
4
3
+
d (2
+
a )
Point
a.
-
9( a
+
bc )
+
3( r
+
34)
a
+
bd
2.5) 2.5 + t
b. 5.5
*
( r
+
 
 
Search WWH ::




Custom Search