0% found this document useful (0 votes)
3 views15 pages

OOP2024 JavaExercises Homework2 JavaLanguageBasics

This document provides exercises on Java programming basics, emphasizing the importance of writing good, maintainable code. It includes specific tasks such as creating number and word guessing games, as well as generating various patterns using loops. Additionally, it highlights coding style, documentation, and the necessity of practice in programming.

Uploaded by

sieuphamx0x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

OOP2024 JavaExercises Homework2 JavaLanguageBasics

This document provides exercises on Java programming basics, emphasizing the importance of writing good, maintainable code. It includes specific tasks such as creating number and word guessing games, as well as generating various patterns using loops. Additionally, it highlights coding style, documentation, and the necessity of practice in programming.

Uploaded by

sieuphamx0x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

HaQT Object-Oriented Programming

Homework 2. Exercises on Java Basics

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: ”Java Style and Commenting Guide”.


• 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 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

1 Exercises on Decision and Loop


Write a Java program called DecisionAndLoopsHomework that implements the following
methods.

1.1 Number Guess


Write a program to play the number guessing game. The program shall generate a random
number between 0 and 99. The player inputs his/her guess, and the program shall response
with ”Try higher”, ”Try lower” or ”You got it in n trials” accordingly. For example:

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 !

The program is designed using 2 functions with prototypes as follows:

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:

f i n a l i n t SECRET NUMBER = ( i n t ) ( Math . random ( ) ∗ 1 0 0 ) ; // t r u n c a t e t o i n t

2
HaQT Object-Oriented Programming

1.2 Word Guess


Write a program to guess a word by trying to guess the individual characters. The word to
be guessed shall be provided by player. Your program shall look like:

Command window

1 Key i n one c h a r a c t e r o r your g u e s s word : t


Trial 1: t t
3 Key i n one c h a r a c t e r o r your g u e s s word : g
Trial 2: t t g
5 Key i n one c h a r a c t e r o r your g u e s s word : e
Trial 3: te t g
7 Key i n one c h a r a c t e r o r your g u e s s word : testing
Congratulation !
9 You g o t i n 4 t r i a l s

The program is designed using 2 functions with prototypes as follows:

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:

// Outer l o o p t o p r i n t each o f t h e rows


2 f o r ( i n t row = 1 ; row <= s i z e ; row ++ ) { // row = 1 , 2 , 3 , . . . , s i z e
// I n n e r l o o p t o p r i n t each o f t h e columns o f a p a r t i c u l a r row
4 f o r ( i n t c o l = 1 ; c o l <= s i z e ; c o l ++ ) { // c o l = 1 , 2 , 3 , . . . , s i z e
System . out . p r i n t ( . . . . . . ) ; // Use print() without newline inside the inner loop
6 ......
}
8
// P r i n t a n e w l i n e a f t e r p r i n t i n g a l l t h e columns
10 System . out . p r i n t l n ( ) ;
}

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

1. Rewrite the above program using nested while-do loops.

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

// Outer l o o p t o p r i n t each o f t h e rows


2 f o r ( i n t row = 1 ; row <= s i z e ; row ++ ) { // row = 1 , 2 , 3 , . . . , s i z e
// I n n e r l o o p t o p r i n t each o f t h e columns o f a p a r t i c u l a r row
4 f o r ( i n t c o l = 1 ; c o l <= s i z e ; c o l ++ ) { // c o l = 1 , 2 , 3 , . . . , s i z e
i f ( ( row % 2 ) = = 0 ) { // row 2 , 4 , 6 , . . .
6 ......
}
8
System . out . p r i n t ( . . . . . . ) ; // Use print() without newline inside the inner loop
10 ......
}
12
// P r i n t a n e w l i n e a f t e r p r i n t i n g a l l t h e columns
14 System . out . p r i n t l n ( ) ;
}

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

1. Use printf() to format the output, e.g., each cell is %4d.

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.

7. The coding pattern is:

1 // Outer l o o p t o p r i n t each o f t h e rows


f o r ( i n t row = 1 ; row <= s i z e ; row ++ ) { // row = 1, 2, 3, ..., size
3 // I n n e r l o o p t o p r i n t each o f t h e columns o f a p a r t i c u l a r row
f o r ( i n t c o l = 1 ; c o l <= s i z e ; c o l ++ ) { // col = 1, 2, 3, ..., size
5 if (......) {
System . out . p r i n t ( ”# ” ) ;
7 } else {
System . out . p r i n t ( ” ” ) ; // Need t o p r i n t t h e ” l e a d i n g ” b l a n k s
9 }
}
11
// P r i n t a n e w l i n e a f t e r p r i n t i n g a l l t h e columns
13 System . out . p r i n t l n ( ) ;
}

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

1. For pattern (a):

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 ......;
}

or, use 2 sequential inner loops to print the columns:

8
HaQT Object-Oriented Programming

1 f o r ( i n t row = 1 ; row <= rows ; row ++ ) {


f o r ( i n t c o l = 1 ; c o l <= rows ; c o l ++ ) {
3 i f ( ( row + c o l >= rows + 1 ) ) {
......
5 } else {
......
7 }
}
9
f o r ( i n t c o l = 2 ; c o l <= rows ; c o l ++ ) { // s k i p c o l = 1
11 i f ( row >= c o l ) {
......
13 } else {
......
15 }
}
17 ......
}

3 Exercises on String and char Operations


Write a Java program called StringAndCharacterHomework that implements the following
methods.

3.1 Exchange Cipher


This simple cipher exchanges ’A’ and ’Z’, ’B’ and ’Y’, ’C’ and ’X’, and so on.
Write a method called exchangeCipher() (with prototype String exchangeCipher(String in-
Str)) that computes the ciphertext; and return the ciphertext in uppercase. Write a method
called testExchangeCipher() that prompts user for a plaintext string consisting of mix-case
letters only, compute the ciphertext; and print the ciphertext in uppercase. For examples,

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

1. Use in.next().toUpperCase() to read an input string and convert it into uppercase to


reduce the number of cases.

2. You can use a big nested-if with 26 cases (’A’ - ’Z’), or use the following relationship:

9
HaQT Object-Oriented Programming

’A’ + ’Z’ == ’B’ + ’Y’ == ’C’ + ’X’ == ... == plainTextChar + cipherTextChar


Hence, cipherTextChar = ’A’ + ’Z’ - plainTextChar

3.2 TestPalindromicWord and TestPalindromicPhrase


A word that reads the same backward as forward is called a palindrome, e.g., ”mom”,
”dad”, ”racecar”, ”madam”, and ”Radar” (case-insensitive). Write a method called isPalin-
dromicWord() (with prototype boolean isPalindromicWord(String inStr)) that checks for
palindromic work. Write a method called testPalindromicWord() that prompts user for a
word and prints ””xxx” is | is not a palindrome”.
A phrase that reads the same backward as forward is also called a palindrome, e.g., ”Madam,
I’m Adam”, ”A man, a plan, a canal - Panama!” (ignoring punctuation and capitaliza-
tion). Modify your methods (called isPalindromicPhrase() and testPalindromicPhrase())
to check for palindromic phrase. Use in.nextLine() to read a line of input.

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 ......

4.2 Matrices (2D Arrays)


Write a Matrix library that supports matrix operations (such as addition, subtraction, mul-
tiplication) via 2D arrays. The operations shall support both double and int. Also write
methods to test all the operations.

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.

5.1 Trigonometric Series


Write methods to compute sin(x) and cos(x) using the following series expansion. The
prototypes of the methods are:

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

5.2 Exponential Series


Write a method to compute the sum of the series. The signature of the method is:

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.

5.3 FactorialInt (Handling Overflow)


Write a method called factorialInt() to list all the factorials that can be expressed as an int
(i.e., 32-bit signed integer in the range of [−2147483648, 2147483647]). Your output shall
look like:

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

1 System . out . p r i n t l n ( I n t e g e r .MAX VALUE) ;


System . out . p r i n t l n ( I n t e g e r . MIN VALUE) ;
3 System . out . p r i n t l n ( I n t e g e r .MAX VALUE + 1 ) ;

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.

5.4 FibonacciInt (Handling Overflow)


Write a method called fibonacciInt() to list all the Fibonacci numbers, which can be expressed
as an int (i.e., 32-bit signed integer in the range of [−2147483648, 2147483647]). The output
shall look like:

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:

System . out . p r i n t l n ( I n t e g e r .MAX VALUE) ;


2 System . out . p r i n t l n ( I n t e g e r . MIN VALUE) ;
System . out . p r i n t l n ( I n t e g e r .MAX VALUE + 1 ) ;

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.

5.5 Number System Conversion


Write a method call toRadix() which converts a positive integer from one radix into another.
The method has the following header:

1 // The i n p u t and output a r e t r e a t e d a s S t r i n g .


p u b l i c s t a t i c S t r i n g toRadix ( S t r i n g in , i n t inRadix , i n t outRadix )

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

Enter a number and r a d i x : A1B2


2 Enter t h e i n p u t r a d i x : 16
Enter t h e output r a d i x : 2
4 ”A1B2” i n r a d i x 16 i s ”1010000110110010” i n r a d i x 2 .

15

You might also like