Java Reference
In-Depth Information
L
ISTING
2.8
SalesTax.java
1
import
java.util.Scanner;
2
3
public class
SalesTax {
4
public static void
main(String[] args) {
5 Scanner input =
new
Scanner(System.in);
6
7 System.out.print(
"Enter purchase amount: "
);
8
double
purchaseAmount = input.nextDouble();
9
10
double
tax = purchaseAmount *
0.06
;
11 System.out.println(
"Sales tax is $"
+ (
int
)(tax *
100
) /
100.0
);
12 }
13 }
casting
Enter purchase amount: 197.55
Sales tax is $11.85
line#
purchaseAmount
tax
output
8
197.55
10
11.853
11
11.85
The variable
purchaseAmount
is
197.55
(line 8). The sales tax is
6%
of the purchase, so
the
tax
is evaluated as
11.853
(line 10). Note that
formatting numbers
tax * 100
is
1185.3
(int)(tax * 100)
is
1185
(int)(tax * 100) / 100.0
is
11.85
So, the statement in line 11 displays the tax
11.85
with two digits after the decimal point.
2.27
✓
✓
Can different types of numeric values be used together in a computation?
Check
2.28
Point
What does an explicit casting from a
double
to an
int
do with the fractional part of
the
double
value? Does casting change the variable being cast?
2.29
Show the following output:
float
f =
12.5F
;
int
i = (
int
)f;
System.out.println(
"f is "
+ f);
System.out.println(
"i is "
+ i);
2.30
If you change
(int)(tax * 100) / 100.0
to
(int)(tax * 100) / 100
in line
11 in Listing 2.8, what will be the output for the input purchase amount of
197.55
?
2.31
Show the output of the following code:
double
amount =
5
;
System.out.println(amount /
2
);
System.out.println(
5
/
2
);
Search WWH ::
Custom Search