Java Reference
In-Depth Information
The program in Listing 2.4 obtains minutes and remaining seconds from an amount of time
in seconds. For example, 500 seconds contains 8 minutes and 20 seconds.
L ISTING 2.4 DisplayTime.java
1
2
3 public class DisplayTime {
4
import java.util.Scanner;
import Scanner
public static void main(String[] args) {
5
6 // Prompt the user for input
7 System.out.print( "Enter an integer for seconds: " );
8
Scanner input = new Scanner(System.in);
create a Scanner
int seconds =
input.nextInt()
;
read an integer
9
10 int minutes = ; // Find minutes in seconds
11 int remainingSeconds = ; // Seconds remaining
12 System.out.println(seconds + " seconds is " + minutes +
13
seconds / 60
divide
remainder
seconds % 60
" minutes and " + remainingSeconds + " seconds" );
14 }
15 }
Enter an integer for seconds:
500 seconds is 8 minutes and 20 seconds
500
line#
seconds
minutes
remainingSeconds
8
500
10
8
11
20
The nextInt() method (line 8) reads an integer for seconds . Line 10 obtains the min-
utes using seconds / 60 . Line 11 ( seconds % 60 ) obtains the remaining seconds after
taking away the minutes.
The + and - operators can be both unary and binary. A unary operator has only one operand;
a binary operator has two. For example, the - operator in -5 is a unary operator to negate num-
ber 5 , whereas the - operator in 4 - 5 is a binary operator for subtracting 5 from 4 .
unary operator
binary operator
Note
Calculations involving floating-point numbers are approximated because these numbers
are not stored with complete accuracy. For example,
floating-point approximation
System.out.println( 1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1 );
displays 0.5000000000000001 , not 0.5 , and
System.out.println( 1.0 - 0.9 );
displays 0.09999999999999998 , not 0.1 . Integers are stored precisely. Therefore,
calculations with integers yield a precise integer result.
 
 
Search WWH ::




Custom Search