OOP2024 JavaExercises Homework2 JavaLanguageBasics
OOP2024 JavaExercises Homework2 JavaLanguageBasics
1. Coding style:
3. The only way to learn programming is program, program and program on chal-
lenging 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 Object-Oriented Programming
Command window
1 Key i n your g u e s s :
50
3 Try higher
70
5 Try lower
65
7 Try lower
61
9 You got i t in 4 t r i a l s !
p u b l i c s t a t i c v o i d guessNumber ( ) ;
2 p u b l i c s t a t i c v o i d guessNumber ( i n t number , Scanner i n ) ;
• void guessNumber(): Generate a random number between 0 and 99, then call the
method void guessNumber(int number, Scanner in) to guess the generated number.
• void guessNumber(int number, Scanner in): The player inputs his/her guess, and the
program shall response with ”Try higher”, ”Try lower” or ”You got it in n trials”
accordingly.
Hints
Use Math.random() to produce a random number in double between 0.0 (inclusive) and 1.0
(exclusive). To produce an int between 0 and 99, use:
2
HaQT Object-Oriented Programming
Command window
p u b l i c s t a t i c v o i d guessWord ( ) ;
2 p u b l i c s t a t i c v o i d guessWord ( S t r i n g g u e s s e d S t r i n g , Scanner i n ) ;
• void guessWord(): Prompt player for a word, then call the method void guessWord(String
guessedString, Scanner in) to guess the word.
• void guessWord(String guessedString, Scanner in): The player inputs his/her guess.
Hints
1. Set up a boolean array (of the length of the word to be guessed) to indicate the positions
of the word that have been guessed correctly.
2. Check the length of the input string to determine whether the player enters a single
character or a guessed word. If the player enters a single character, check it against
the word to be guessed, and update the boolean array that keeping the result so far.
Try
Try retrieving the word to be guessed from a text file (or a dictionary) randomly.
2 Exercises on Nested-Loops
Write a Java program called NestedLoopsExercise that implements the following methods.
3
HaQT Object-Oriented Programming
2.1 SquarePattern
Write a method called squarePattern() (with prototype void squarePattern(int n)) that
prints the following square pattern using two nested for-loops. Write a method called test-
SquarePattern() prompts user for the size (a non-negative integer in int); and prints the
square pattern.
Command window
Enter the s i z e : 5
2 ### ##
### ##
4 ### ##
### ##
6 ### ##
Hints
The code pattern for printing 2D patterns using nested loops is:
Notes
1. You should name the loop indexes row and col, NOT i and j, or x and y, or a and b,
which are meaningless.
2. The row and col could start at 1 (and upto size), or start at 0 (and upto size − 1). As
computer counts from 0, it is probably more efficient to start from 0. However, since
humans counts from 1, it is easier to read if you start from 1.
Try
4
HaQT Object-Oriented Programming
2.2 CheckerPattern
Write a method called checkerPattern() (with prototype void checkerPattern(int n)) that
prints the following checkerboard pattern. Write a method called testCheckerPattern() that
prompts user for the size (a non-negative integer in int); and prints the checkerboard pattern.
Command window
1 Enter t h e s i z e : 7
#######
3 #######
#######
5 #######
#######
7 #######
#######
Hints
2.3 TimeTable
Write a method called timeTable() (with prototype void timeTable(int n)) that prints the
multiplication table as the following table. Write a method called testTimeTable() that
prompts user for the size (a positive integer in int); and prints the multiplication table.
5
HaQT Object-Oriented Programming
Command window
1 Enter t h e s i z e : 10
∗ | 1 2 3 4 5 6 7 8 9 10
3 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
1 | 1 2 3 4 5 6 7 8 9 10
5 2 | 2 4 6 8 10 12 14 16 18 20
3 | 3 6 9 12 15 18 21 24 27 30
7 4 | 4 8 12 16 20 24 28 32 36 40
5 | 5 10 15 20 25 30 35 40 45 50
9 6 | 6 12 18 24 30 36 42 48 54 60
7 | 7 14 21 28 35 42 49 56 63 70
11 8 | 8 16 24 32 40 48 56 64 72 80
9 | 9 18 27 36 45 54 63 72 81 90
13 10 | 10 20 30 40 50 60 70 80 90 100
Hints
2.4 TriangularPattern
Write 4 methods called triangularPatternX() (with prototype void triangularPatternX(int
n), X = A, B, C, D) that prints each of the patterns as shown. Write a method called
testTriangularPattern() prompts user for the size (a non-negative integer in int); and prints
each of the patterns.
Command window
1 Enter t h e s i z e : 8
3 # # # # # #### #### # # # # #
# # # # # # ### ### # # # # # #
5 # # # # # # # ## ## # # # # # # #
# # # # # # # # # # # # # # # # # #
7 # # # ## # # # # # # # # ## # # #
# # # ### # # # # # # ### # # #
9 # # # #### # # # # #### # # #
# # # ##### # # ##### # # #
11 (a) (b) (c) (d)
Hints
1. On the main diagonal, row = col. On the opposite diagonal, row + col = size + 1,
where row and col begin from 1.
2. You need to print the leading blanks, in order to push the # to the right. The trailing
blanks are optional, which does not affect the pattern.
6
HaQT Object-Oriented Programming
3. For pattern (a), if (row ≥ col) print #. Trailing blanks are optional.
4. For pattern (b), if (row + col ≤ size + 1) print #. Trailing blanks are optional.
5. For pattern (c), if (row ≥ col) print #; else print blank. Need to print the leading
blanks.
6. For pattern (d), if (row + col ≥ size + 1) print #; else print blank. Need to print the
leading blanks.
2.5 BoxPattern
Write 4 methods called boxPatternX() (with prototype void boxPatternX(int n), X = A,
B, C, D) that prints the pattern as shown. Write a method called testBoxPattern() that
prompts user for the size (a non-negative integer in int); and prints the patterns.
Command window
Enter t h e s i z e : 8
2
####### ####### ####### ##### ##
4 # # # # # #
# # # # # #
6 # # # # #
# # # # # #
8 # # # # # #
####### ####### ####### ##### ##
10 (a) (b) (c) (d)
Hints
7
HaQT Object-Oriented Programming
1. On the main diagonal, row = col. On the opposite diagonal, row + col = size + 1,
where row and col begin from 1.
2. For pattern (a), if (row == 1 | | row == size | | col == 1 | | col == size) print #; else
print blank. Need to print the intermediate blanks.
3. For pattern (b), if (row == 1 | | row == size | | row == col) print #; else print blank.
2.6 HillPattern
Write 4 methods called hillPatternX() (with prototype void hillPatternX(int n) , X = A,
B, C, D) that prints the pattern as shown. Write a method called testHillPatternX() that
prompts user for the size (a non-negative integer in int); and prints the patterns.
Command window
Enter t h e rows : 5
2
# ######### # # ####### #
4 ### ####### ### # ### ### #
##### ##### # ### # # ## ## #
6 ####### ### # # ### ## # # # #
######### # ## # ### #### #
8 (a) (b) # # ### ## # # # #
# ### # # ## ## #
10 ### # ### ### #
# # ####### #
12 (c) (d)
Hints
f o r ( i n t row = 1 ; . . . . . . ) {
2 // numCol = 2∗numRows − 1
for ( int col = 1; . . . . . . ) {
4 i f ( ( row + c o l >= numRows + 1 ) && ( row >= c o l − numRows + 1 ) ) {
......;
6 } else {
......;
8 }
}
10 ......;
}
8
HaQT Object-Oriented Programming
Command window
Enter a p l a i n t e x t s t r i n g : abcXYZ
2 The c i p h e r t e x t s t r i n g i s : ZYXCBA
Hints
2. You can use a big nested-if with 26 cases (’A’ - ’Z’), or use the following relationship:
9
HaQT Object-Oriented Programming
Hints
1. Maintain two indexes, forwardIndex (fIdx ) and backwardIndex (bIdx ), to scan the
phrase forward and backward.
int fIdx = 0;
2 i n t bIdx = s t r L e n − 1 ;
w h i l e ( f I d x < bIdx ) {
4 ......
++ f I d x ;
6 - - bIdx ;
}
8
// o r
10 f o r ( i n t f I d x = 0 , bIdx = s t r L e n − 1 ; f I d x < bIdx ; ++ f I d x , - - bIdx )
,→ {
......
12 }
2. You can check if a char c is a letter either using built-in boolean function Charac-
ter.isLetter(c); or boolean expression (c ≥ ’a’ && c ≤ ’z’). Skip the index if it does
not contain a letter.
4 Exercises on Array
4.1 PrintArrayInStars
Write a Java program called ArrayHomework that implements the following methods. Write
a method called printArrayInStars() (with prototype void printArrayStars(Scanner in)) which
10
HaQT Object-Oriented Programming
prompts user for the number of items in an array (a non-negative integer), and saves it in an
int variable called NUM ITEMS. It then prompts user for the values of all the items (non-
negative integers) and saves them in an int array called items. The program shall then print
the contents of the array in a graphical form, with the array index and values represented
by number of stars. For examples,
Command window
1 Enter t h e number o f i t e m s : 5
Enter t h e v a l u e o f a l l i t e m s ( s e p a r a t e d by s p a c e ) : 7 4 3 0 7
3 0: ∗∗∗∗∗∗∗(7)
1: ∗∗∗∗(4)
5 2: ∗∗∗(3)
3: (0)
7 4: ∗∗∗∗∗∗∗(7)
Hints
1 // D e c l a r e v a r i a b l e s
f i n a l i n t NUM ITEMS;
3 i n t [ ] i t e m s ; // Declare array name, to be allocated after NUM ITEMS is known
......
5 ......
7 // P r i n t a r r a y i n ” i n d e x : number o f s t a r s ” u s i n g a n e s t e d −l o o p
// Take note that rows are the array indexes and columns are the value in that index
9 f o r ( i n t i d x = 0 ; i d x < i t e m s . l e n g t h ; ++ i d x ) { // row
System . out . p r i n t ( i d x + ” : ” ) ;
11 // P r i n t v a l u e a s t h e number o f s t a r s
f o r ( i n t starNo = 1 ; starNo <= i t e m s [ i d x ] ; ++ starNo ) { // column
13 System . out . p r i n t ( ” ∗ ” ) ;
}
15 ......
}
17 ......
Hints
11
HaQT Object-Oriented Programming
1 p u b l i c c l a s s Matrix {
// Method s i g n a t u r e s
3 p u b l i c s t a t i c v o i d p r i n t ( i n t [ ] [ ] matrix ) ;
p u b l i c s t a t i c v o i d p r i n t ( d o u b l e [ ] [ ] matrix ) ;
5
// Used i n add ( ) , s u b t r a c t ( )
7 p u b l i c s t a t i c b o o l e a n haveSameDimension ( i n t [ ] [ ] matrix1 ,
i n t [ ] [ ] matrix2 ) ;
9 p u b l i c s t a t i c b o o l e a n haveSameDimension ( d o u b l e [ ] [ ] matrix1 ,
d o u b l e [ ] [ ] matrix2 ) ;
11
p u b l i c s t a t i c i n t [ ] [ ] add ( i n t [ ] [ ] matrix1 , i n t [ ] [ ] matrix2 ) ;
13 p u b l i c s t a t i c d o u b l e [ ] [ ] add ( d o u b l e [ ] [ ] matrix1 ,
d o u b l e [ ] [ ] matrix2 ) ;
15
p u b l i c s t a t i c i n t [ ] [ ] s u b t r a c t ( i n t [ ] [ ] matrix1 , i n t [ ] [ ] matrix2 ) ;
17 p u b l i c s t a t i c d o u b l e [ ] [ ] s u b t r a c t ( d o u b l e [ ] [ ] matrix1 ,
d o u b l e [ ] [ ] matrix2 ) ;
19
p u b l i c s t a t i c i n t [ ] [ ] m u l t i p l y ( i n t [ ] [ ] matrix1 , i n t [ ] [ ] matrix2 ) ;
21 p u b l i c s t a t i c d o u b l e [ ] [ ] m u l t i p l y ( d o u b l e [ ] [ ] matrix1 ,
d o u b l e [ ] [ ] matrix2 ) ;
23
......
25 }
5 Exercises on Method
Write a Java program called MathLibraryHomework that implements the following methods.
1 // x i n r a d i a n s , NOT d e g r e e s
p u b l i c s t a t i c d o u b l e s i n ( d o u b l e x , i n t numTerms ) ;
3 p u b l i c s t a t i c d o u b l e c o s ( d o u b l e x , i n t numTerms ) ;
x3 x5 x7 x9
sin(x) = x − + − + − ···
3! 5! 7! 9!
x2 x4 x6 x8
cos(x) = 1 − + − + − ···
2! 4! 6! 8!
12
HaQT Object-Oriented Programming
Write a method called testTrigonometric() that prompts user for x value (in double) and
numT erms (in int) value, then compute the sin and cosine values of x. Compare the
values computed using the series with the JDK methods Math.sin(), Math.cos() at x =
0, π/6, π/4, π/3, π/2 using various numbers of terms.
Hints
Do not use int to compute the factorial; as factorial of 13 is outside the int range. Avoid
generating large numerator and denominator. Use double to compute the terms as:
xn x
x x
= ... .
n! n n−1 1
1 p u b l i c s t a t i c d o u b l e s p e c i a l S e r i e s ( d o u b l e x , i n t numTerms ) ;
1 x3 1 × 3 x5 1 × 3 × 5 x7 1 × 3 × 5 × 7 x9
x+ × + × + × + × + · · · ; −1 ≤ x ≤ 1.
2 3 2×4 5 2×4×6 7 2×4×6×8 9
Also write a method to test the sum of the series called testSpecialSeries(), which prompts
user for x value (in double) and numT erms (in int) values, then computes the sum of the
series.
Command window
1 The f a c t o r i a l of 1 i s 1
The f a c t o r i a l of 2 i s 2
3 ...
The f a c t o r i a l o f 12 i s 479001600
5 The f a c t o r i a l o f 13 i s out o f r a n g e
Hints
The maximum and minimum values of a 32-bit int are kept in constants Integer.MAX VALUE
and Integer.MIN VALUE, respectively. Try these statements:
13
HaQT Object-Oriented Programming
Take note that in the third statement, Java Runtime does not flag out an overflow error,
but silently wraps the number around. Hence, you cannot use F (n) ∗ (n + 1) > Inte-
ger.MAX VALUE to check for overflow. Instead, overflow occurs for F (n + 1) if (Inte-
ger.MAX VALUE / Factorial(n)) < (n + 1), i.e., no more room for the next number.
Try
Modify your program called factorialLong() to list all the factorial that can be expressed
as a long (64-bit signed integer). The maximum value for long is kept in a constant called
Long.MAX VALUE.
Command window
1 F(0) = 1
F(1) = 1
3 F(2) = 2
...
5 F( 4 5 ) = 1836311903
F( 4 6 ) i s out o f t h e r a n g e o f i n t
Hints
The maximum and minimum values of a 32-bit int are kept in constants Integer.MAX VALUE
and Integer.MIN VALUE, respectively. Try these statements:
Take note that in the third statement, Java Runtime does not flag out an overflow error, but
silently wraps the number around. Hence, you cannot use F (n) = F (n − 1) + F (n − 2) >
Integer.MAX VALUE to check for overflow. Instead, overflow occurs for F (n) if Inte-
14
HaQT Object-Oriented Programming
ger.MAX VALUE –F (n − 1) < F (n − 2) (i.e., no more room for the next Fibonacci number).
Try
Write a similar method called tribonacciInt() for Tribonacci numbers.
Write a method called testNumberConversion(), which prompts the user for an input string,
an input radix, and an output radix, and display the converted number. The output shall
look like:
Command window
15