Java Reference
In-Depth Information
Listing 3.8 gives the program that lets the user enter a year and checks whether it is a leap
year.
L ISTING 3.8 LeapYear.java
1 import java.util.Scanner;
2
3 public class LeapYear {
4 public static void main(String[] args) {
5 // Create a Scanner
6 Scanner input = new Scanner(System.in);
7 System.out.print( "Enter a year: " );
8
int year = input.nextInt();
input
9
10
// Check if the year is a leap year
11
boolean isLeapYear =
leap year?
12
(year % 4 == 0 && year % 100 != 0 ) || (year % 400 == 0 )
;
13
14 // Display the result
15 System.out.println(year + " is a leap year? " + isLeapYear);
16 }
17 }
display result
Enter a year:
2008 is a leap year? true
2012
1900
Enter a year:
1900 is a leap year? false
Enter a year:
2002 is a leap year? false
2002
3.13 Case Study: Lottery
The lottery program involves generating random numbers, comparing digits, and
using Boolean operators.
Key
Point
Suppose you want to develop a program to play lottery. The program randomly generates a
lottery of a two-digit number, prompts the user to enter a two-digit number, and determines
whether the user wins according to the following rules:
1. If the user input matches the lottery number in the exact order, the award is $10,000.
2. If all the digits in the user input match all the digits in the lottery number, the award is
$3,000.
3. If one digit in the user input matches a digit in the lottery number, the award is $1,000.
The complete program is shown in Listing 3.9.
L ISTING 3.9 Lottery.java
1 import java.util.Scanner;
2
3 public class Lottery {
4
public static void main(String[] args) {
5
// Generate a lottery number
 
 
 
Search WWH ::




Custom Search