Java Reference
In-Depth Information
Remainder is very useful in programming. For example, an even number % 2 is always 0
and an odd number % 2 is always 1 . Thus, you can use this property to determine whether a
number is even or odd. If today is Saturday, it will be Saturday again in 7 days. Suppose you
and your friends are going to meet in 10 days. What day is in 10 days? You can find that the
day is Tuesday using the following expression:
Day 6 in a week is Saturday
A week has 7 days
(6 + 10) % 7 is 2
After 10 days Day 2 in a week is Tuesday
Note: Day 0 in a week is Sunday
The program in Listing 2.5 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.5
DisplayTime.java
1 import java.util.Scanner;
2
3 public class DisplayTime {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6 // Prompt the user for input
7 System.out.print( "Enter an integer for seconds: " );
8
import Scanner
create a Scanner
int seconds = input.nextInt();
read an integer
9
10 int minutes = seconds / 60 ; // Find minutes in seconds
11 int remainingSeconds = seconds % 60 ; // Seconds remaining
12 System.out.println(seconds + " seconds is " + minutes +
13
divide
remainder
" minutes and " + remainingSeconds + " seconds" );
14 }
15 }
Enter an integer for seconds: 500
500 seconds is 8 minutes and 20 seconds
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 number 5 , whereas the - operator in 4 - 5 is a binary operator for subtracting 5
from 4 .
unary operator
binary operator
 
 
Search WWH ::




Custom Search