HaQT Fundamental Programming
Lab 2. Java Exercises on Decision
Writing Good Programs
The only way to learn programming is program, program and program. Learning programming
is like learning cycling, swimming or any other sports. You can’t learn by watching or reading
books. Start to program immediately. On the other hands, to improve your programming, you
need to read many books and study how the masters program.
It is easy to write programs that work. It is much harder to write programs that not only work
but also easy to maintain and understood by others – I call these good programs. In the real
world, writing program is not meaningful. You have to write good programs, so that others can
understand and maintain your programs.
Pay particular attention to:
1. Coding style:
Read Java code convention: "Google Java Style Guide" or "Oracle Java Code Con-
ventions".
Follow the Java Naming Conventions for variables, methods, and classes STRICTLY.
Use CamelCase for names. Variable and method names begin with lowercase, while
class names begin with uppercase. Use nouns for variables (e.g., radius) and class
names (e.g., Circle). Use verbs for methods (e.g., getArea(), isEmpty()).
Use Meaningful Names: Do not use names like a, b, c, d, x, x1, x2, and x1688
- they are meaningless. Avoid single-alphabet names like i, j, k. They are easy to
type, but usually meaningless. Use single-alphabet names only when their meaning
is clear, e.g., x, y, z for co-ordinates and i for array index. Use meaningful names like
row and col (instead of x and y, i and j, x1 and x2), numStudents (not n), maxGrade,
size (not n), and upperbound (not n again). Differentiate between singular and plural
nouns (e.g., use books for an array of books, and book for each item).
Use consistent indentation and coding style. Many IDEs (such as Eclipse / NetBeans)
can re-format your source codes with a single click.
2. Program Documentation: Comment! Comment! and more Comment to explain your
code to other people and to yourself three days later.
3. The only way to learn programming is program, program and program on challenging
problems. The problems in this tutorial are certainly NOT challenging. There are tens of
thousands of challenging problems available – used in training for various programming
contests (such as International Collegiate Programming Contest (ICPC), International
Olympiad in Informatics (IOI)).
1
HaQT Fundamental Programming
1 Exercises on Decision
1.1 CheckPassFail
Write a program called CheckPassFail which prints "PASS" if the int variable "mark" is more than
or equal to 50; or prints "FAIL" otherwise. The program shall always print “DONE” before exiting.
Hints
Use ≥ for greater than or equal to comparison.
1 / **
* Trying i f = e l s e s t a t e m e n t .
3 */
import j a v a . u t i l . Sc anne r ;
5
p u b l i c c l a s s CheckPassFail { // Save a s " C h e c k P a s s F a i l . j a v a "
7 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { // Program e n t r y p o i n t
S ca nner i n p u t = new S canne r ( System . i n ) ;
9 System . out . p r i n t ( " I n p u t your mark : " ) ;
i n t mark = i n p u t . n e x t I n t ( ) ; // S e t t h e v a l u e o f "mark" h e r e !
11 input . c l o s e () ;
13 System . out . p r i n t l n ( "The mark i s " + mark ) ;
15 // i f = e l s e s t a t e m e n t
if ( ...... ) {
17 System . out . p r i n t l n ( ...... );
} else {
19 System . out . p r i n t l n ( ...... );
}
21 System . out . p r i n t l n ( ...... );
}
23 }
Try mark = 0, 49, 50, 51, 100 and verify your results.
Take note of the source-code indentation!!! Whenever you open a block with ’{’, indent all the state-
ments inside the block by 3 (or 4 spaces). When the block ends, un-indent the closing ’}’ to align with
the opening statement.
1.2 CheckOddEven
Write a program called CheckOddEven which prints "Odd Number" if the int variable “number”
is odd, or “Even Number” otherwise. The program shall always print “Bye!” before exiting.
Hints
n is an even number if (n % 2) is 0; otherwise, it is an odd number. Use == for comparison, e.g.,
(n % 2) == 0.
2
HaQT Fundamental Programming
1 / **
* Trying i f = e l s e s t a t e m e n t and modulus (%) o p e r a t o r .
3 */
import j a v a . u t i l . Sc anne r ;
5
p u b l i c c l a s s CheckOddEven { // Save a s "CheckOddEven . j a v a "
7 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { // Program e n t r y p o i n t
S ca nner i n p u t = new S canne r ( System . i n ) ;
9 System . out . p r i n t ( " I n p u t number : " ) ;
i n t number = i n p u t . n e x t I n t ( ) ; // S e t t h e v a l u e o f "number" h e r e !
11 input . c l o s e () ;
13 System . out . p r i n t l n ( "The number i s " + number ) ;
if ( ...... ) {
15 System . out . p r i n t l n ( ...... ); // even number
} else {
17 System . out . p r i n t l n ( ...... ); // odd number
}
19 System . out . p r i n t l n ( ...... );
}
21 }
Try number = 0, 1, 88, 99, −1, −2 and verify your results.
Again, take note of the source-code identation! Make it a good habit to ident your code properly, for
ease of reading your program.
1.3 PrintNumberInWord
Write a program called PrintNumberInWord which prints "ONE", "TWO",... , "NINE", "OTHER"
if the int variable "number" is 1, 2, ..., 9, or other, respectively. Use (a) a "nested-if" statement; (b) a
"switch-case-default" statement.
Hints
1 / **
* Trying n e s t e d = i f and s w i t c h =c a s e s t a t e m e n t s .
3 */
import j a v a . u t i l . Sc anne r ;
5
p u b l i c c l a s s PrintNumberInWord { // Save a s " PrintNumberInWord . j a v a "
7 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
S ca nner i n p u t = new S canne r ( System . i n ) ;
9 System . out . p r i n t ( " I n p u t number : " ) ;
i n t number = i n p u t . n e x t I n t ( ) ; // S e t t h e v a l u e o f "number" h e r e !
11 input . c l o s e () ;
13 // Using n e s t e d = i f
3
HaQT Fundamental Programming
i f ( number = = 1 ) { // Use = = f o r c o m p a r i s o n
15 System . out . p r i n t l n ( ...... );
} else if ( ...... ) {
17 ......
} else if ( ...... ) {
19 ......
} else {
21 ......
}
23
// Using s w i t c h =c a s e = d e f a u l t
25 s w i t c h ( number ) {
case 1:
27 System . out . p r i n t l n ( ...... );
break ; // Don ’ t f o r g e t t h e " b r e a k " a f t e r each c a s e !
29 case 2:
System . out . p r i n t l n ( ...... );
31 break ;
......
33 ......
default :
35 System . out . p r i n t l n ( ...... );
}
37 }
}
Try number = 0, 1, 2, 3, ..., 9, 10 and verify your results.
1.4 PrintDayInWord
Write a program called PrintDayInWord which prints "Sunday", "Monday", ... "Saturday" if the int
variable "dayNumber " is 0, 1, ..., 6, respectively. Otherwise, it shall print "Not a valid day". Use (a) a
"nested-if" statement; (b) a "switch-case-default" statement.
Try dayNumber = 0, 1, 2, 3, 4, 5, 6, 7 and verify your results.
1.5 QuadraticEquationsSolver
Write a Java program to solve quadratic equations (use if, else if and else).
Sample output
Command window
Input a : 1
2 Input b : 5
Input c : 2
4 The r o o t s a r e = 0.4384471871911697 and = 4.561552812808831
4
HaQT Fundamental Programming
Hints
import j a v a . u t i l . Sc anne r ;
2
public c l a s s QuadraticEquationsSolver {
4 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] Strings ) {
S ca nner i n p u t = new S canne r ( System . i n ) ;
6 System . out . p r i n t ( " I n p u t a : " ) ;
d o u b l e a = i n p u t . nextDouble ( ) ;
8 System . out . p r i n t ( " I n p u t b : " ) ;
d o u b l e b = i n p u t . nextDouble ( ) ;
10 System . out . p r i n t ( " I n p u t c : " ) ;
d o u b l e c = i n p u t . nextDouble ( ) ;
12 input . c l o s e () ;
14 double d e l t a = . . . ;
16 i f ( delta > 0.0) {
double root1 = . . . ;
18 double root2 = . . . ;
System . out . p r i n t l n ( "The r o o t s a r e " + r o o t 1 + " and " + r o o t 2 ) ;
20 } else i f ( delta == 0.0) {
double root1 = ;
22 System . out . p r i n t l n ( "The r o o t i s " + r o o t 1 ) ;
} else {
24 System . out . p r i n t l n ( "The e q u a t i o n has no r e a l r o o t s . " ) ;
}
26 }
}
1.6 LeapYear
Write a Java program that takes a year from user and print whether that year is a leap year or not.
5
HaQT Fundamental Programming
Sample Output:
Command window
1 I n p u t t h e y e a r : 2016
2016 i s a l e a p y e a r
Hints
import j a v a . u t i l . Sc anne r ;
2
p u b l i c c l a s s LeapYear {
4 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
S ca nner i n = new Scann er ( System . i n ) ;
6 System . out . p r i n t ( " I n p u t t h e y e a r : " ) ;
i n t year = in . nextInt ( ) ;
8 in . close () ;
10 boolean i s D i v i s i b l e B y 4 = ( year % 4) = = 0 ;
boolean i s D i v i s i b l e B y 1 0 0 = ( year % 100) = = 0 ;
12 b o o l e a n i s D i v i s i b l e B y 4 0 0 = ( y e a r % 400 = = 0 ) ;
14 i f ( isDivisibleBy400 | | ( i s D i v i s i b l e B y 4 && ( ! i s D i v i s i b l e B y 1 0 0 ) ) ) {
System . out . p r i n t l n ( y e a r + " i s . . . a leap year " ) ;
16 } else {
System . out . p r i n t l n ( y e a r + " i s . . . a leap year " ) ;
18 }
}
20 }
1.7 DaysInMonthFinder
Write a Java program to find the number of days in a month.
Sample Output
6
HaQT Fundamental Programming
Command window
I n p u t a month number : 2
2 I n p u t a y e a r : 2016
February 2016 has 29 days
Hints
1 import j a v a . u t i l . Sc anne r ;
3 p u b l i c c l a s s DaysInMonthFinder {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] strings ) {
5 S ca nner i n p u t = new S canne r ( System . i n ) ;
7 System . out . p r i n t ( " I n p u t a month number : " ) ;
i n t month = i n p u t . n e x t I n t ( ) ;
9
System . out . p r i n t ( " I n p u t a y e a r : " ) ;
11 i n t year = input . nextInt ( ) ;
7
HaQT Fundamental Programming
13 input . c l o s e () ;
15 i n t numberOfDaysInMonth = 0 ;
S t r i n g NameOMonth = "Unknown" ;
17
s w i t c h ( month ) {
19 case 1:
NameOMonth = " January " ;
21 numberOfDaysInMonth = 3 1 ;
break ;
23 case 2:
NameOMonth = " February " ;
25 i f ( isLeapYear ( year ) ) {
numberOfDaysInMonth = 2 9 ;
27 } else {
numberOfDaysInMonth = 2 8 ;
29 }
break ;
31 case 3:
...
33 case 4:
...
35 ...
...
37 ...
case 12:
39 ...
}
41
System . out . p r i n t (NameOMonth + " " + y e a r + " has " + numberOfDaysInMonth + " days \n" ) ;
43 }
45 p u b l i c s t a t i c boolean isLeapYear ( i n t year ) {
boolean r e s u l t = . . . ;
47 return r e s u l t ;
}
49 }
1.8 CharacterPrinter
Write a Java program that takes the user to provide a single character from the alphabet. Print Vowel
or Consonant, depending on the user input. If the user input is not a letter (between a and z or A and
Z), or is a string of length > 1, print an error message.
8
HaQT Fundamental Programming
Sample Output
Command window
1 I n p u t an a l p h a b e t : P
Input l e t t e r i s Consonant
Hints
import j a v a . u t i l . Sc anne r ;
2
public c l a s s CharacterPrinter {
4 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
S ca nner i n = new Scann er ( System . i n ) ;
6
System . out . p r i n t ( " I n p u t an a l p h a b e t : " ) ;
8 S t r i n g i n p u t S t r i n g = in . next ( ) ;
10 in . close () ;
12 if ( ( i n p u t S t r i n g . l e n g t h ( ) <= 0 ) | | ( i n p u t S t r i n g . l e n g t h ( ) > 1 ) ) {
System . out . p r i n t l n ( " E r r o r . Not a s i n g l e c h a r a c t e r . " ) ;
14 return ;
}
16
c h a r inputChar = i n p u t S t r i n g . charAt ( 0 ) ;
18
if ( ... ) {
9
HaQT Fundamental Programming
20 System . out . p r i n t l n ( "Error. Not a letter. Enter uppercase or lowercase letter." ) ;
return ;
22 }
24 if ( ... ) {
System . out . p r i n t l n ( " I n p u t l e t t e r i s Vowel " ) ;
26 } else {
System . out . p r i n t l n ( " I n p u t l e t t e r i s Consonant " ) ;
28 }
}
30
p u b l i c s t a t i c b o o l e a n i s U p p e r c a s e ( c h a r ch ) {
32 b o o l e a n r e s u l t = ( ch >= 6 5 ) && ( ch <= 9 0 ) ;
return r e s u l t ;
34 }
36 p u b l i c s t a t i c b o o l e a n i s L o w e r c a s e ( c h a r ch ) {
...
38 }
40 p u b l i c s t a t i c b o o l e a n i s V o w e l s ( c h a r ch ) {
s w i t c h ( ch ) {
42 case ’a ’ :
c a s e ’A ’ :
44 case ’ e ’ :
c a s e ’E ’ :
46 case ’ i ’ :
case ’ I ’ :
48 case ’o ’ :
c a s e ’O ’ :
50 case ’u ’ :
c a s e ’U ’ :
52 return true ;
54 return f a l s e ;
}
56 }
}
1.9 PensionContributionCalculator
Both the employer and the employee are mandated to contribute a certain percentage of the employee’s
salary towards the employee’s pension fund. The rate is tabulated as follows:
Employee’s Age Employee Rate (%) Employer Rate (%)
55 and below 20 17
above 55 to 60 13 13
above 60 to 65 7.5 9
above 65 5 7.5
10
HaQT Fundamental Programming
However, the contribution is subjected to a salary ceiling of $6, 000. In other words, if an employee
earns $6, 800, only $6, 000 attracts employee’s and employer’s contributions, the remaining $800 does
not.
Write a program called PensionContributionCalculator that reads the monthly salary and age (in
int) of an employee. Your program shall calculate the employee’s, employer’s and total contributions
(in double); and print the results rounded to 2 decimal places. For examples,
Command window
1 Enter t h e monthly s a l a r y : $3000
Enter t h e age : 30
3 The employee ’ s c o n t r i b u t i o n i s : $600 . 0 0
The employer ’ s c o n t r i b u t i o n i s : $510 . 0 0
5 The t o t a l c o n t r i b u t i o n i s : $1110 . 0 0
Hints
1 // D e c l a r e c o n s t a n t s
f i n a l i n t SALARY_CEILING = 6 0 0 0 ;
3 f i n a l d o u b l e EMPLOYEE_RATE_55_AND_BELOW = 0 . 2 ;
f i n a l d o u b l e EMPLOYER_RATE_55_AND_BELOW = 0 . 1 7 ;
5 f i n a l d o u b l e EMPLOYEE_RATE_55_TO_60 = 0 . 1 3 ;
f i n a l d o u b l e EMPLOYER_RATE_55_TO_60 = 0 . 1 3 ;
7 f i n a l d o u b l e EMPLOYEE_RATE_60_TO_65 = 0 . 0 7 5 ;
f i n a l d o u b l e EMPLOYER_RATE_60_TO_65 = 0 . 0 9 ;
9 f i n a l d o u b l e EMPLOYEE_RATE_65_ABOVE = 0 . 0 5 ;
f i n a l d o u b l e EMPLOYER_RATE_65_ABOVE = 0 . 0 7 5 ;
11
// D e c l a r e v a r i a b l e s
13 int salary ;
i n t age ; // t o be i n p u t
15
int contributableSalary ;
17 double employeeContribution ;
double employerContribution ;
19 double t o t a l C o n t r i b u t i o n ;
......
21
// Check t h e c o n t r i b u t i o n cap
23 contributableSalary = . . . . . .
25 // Compute v a r i o u s c o n t r i b u t i o n s i n " d o u b l e " u s i n g a n e s t e d = i f t o h a n d l e 4 c a s e s
i f ( age <= 5 5 ) { // 55 and below
27 ......
} else i f ( age <= 6 0 ) { // ( 6 0 , 6 5 ]
29 ......
} else i f ( age <= 6 5 ) { // ( 5 5 , 6 0 ]
31 ......
} else { // above 65
11
HaQT Fundamental Programming
33 ......
}
35 // A l t e r n a t i v e l y ,
// i f ( age > 6 5 ) ......
37 // e l s e i f ( age > 6 0 ) ......
// e l s e i f ( age > 5 5 ) ......
39 // e l s e ......
12