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

Java Methods

The document provides a comprehensive guide on writing good Java programs, emphasizing the importance of coding style, documentation, and practice. It includes exercises on methods such as exponentiation, checking for the digit '8', and various array manipulations, along with guidelines for method signatures and testing. Additionally, it covers a program for calculating statistics from grades, highlighting the need for clarity and maintainability in programming.

Uploaded by

ddddhoa
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 views9 pages

Java Methods

The document provides a comprehensive guide on writing good Java programs, emphasizing the importance of coding style, documentation, and practice. It includes exercises on methods such as exponentiation, checking for the digit '8', and various array manipulations, along with guidelines for method signatures and testing. Additionally, it covers a program for calculating statistics from grades, highlighting the need for clarity and maintainability in programming.

Uploaded by

ddddhoa
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

HaQT Java Programming

Lab 7. Java Exercises on Methods

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). Dierentiate 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 / Net-
Beans) 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 Java Programming

1 Exercises on Methods
1.1 exponent()

Write a method called exponent(int base, int exp) that returns an int value of base raises to the power
of exp. The signature of the method is:

1 public static int exponent ( i n t base , int exp ) ;

Assume that exp is a non-negative integer and base is an integer. Do not use any Math library functions.
Also write the main() method that prompts user for the base and exp; and prints the result. For
example,

Command window

1 Enter the base : 3

Enter the exponent : 4

3 3 raises to the power of 4 is : 81

Hints

1 . . . . . .

public class Exponent {

3 public static void main ( S t r i n g [ ] args ) {

// Declare variables

5 int exp ; // exponent ( non =n e g a t i v e integer )

int base ; // base ( integer )

7 . . . . . .

// Prompt and read exponent and base

9 . . . . . .

// Print result

11 System . o u t . p r i n t l n ( b a s e + " raises to the power of " + exp + " is : " + exponent

,→ ( base , exp ) ) ;

13
// Returns " base " raised to the power " exp "

15 public static int exponent ( i n t base , int exp ) {

int product = 1; // resulting product

17
// Multiply product and base for exp number of times

19 for ( . . . . . . ) {

product *= base ;

21 }

23 return product ;

2
HaQT Java Programming

25 }

1.2 hasEight()

Write a boolean method called hasEight(), which takes an int as input and returns true if the number
contains the digit 8 (e.g., 18, 168, 1288). The signature of the method is as follows:

1 public static boolean hasEight ( i n t number ) ;

Write a program called MagicSum, which prompts user for integers (or −1 to end), and produce the
sum of numbers containing the digit 8. Your program should use the above methods. A sample output
of the program is as follows:

Command window

1 Enter a positive integer ( or =1 to end ) : 1

Enter a positive integer ( or =1 to end ) : 2

3 Enter a positive integer ( or =1 to end ) : 3

Enter a positive integer ( or =1 to end ) : 8

5 Enter a positive integer ( or =1 to end ) : 88

Enter a positive integer ( or =1 to end ) : =1


7 The magic sum is : 96

Hints
1. The coding pattern to repeat until input is −1 (called sentinel value) is:

1 final int SENTINEL = = 1; // Terminating input

int number ;

3
// Read first input to " seed " the while loop

5 System . o u t . p r i n t ( " E n t e r a positive integer ( or =1 to end ) : ") ;

number = in . nextInt () ;

7
while ( number != SENTINEL ) { // Repeat until input is =1
9 . . . . . .

. . . . . .

11
// Read next input . Repeat if the input is not the SENTINEL

13 // Take note that you need to repeat these codes !

System . o u t . p r i n t ( " E n t e r a positive integer ( or =1 to end ) : ") ;

15 number = in . nextInt () ;

3
HaQT Java Programming

2. You can either repeatably use modulus/divide (n % 10 and n = n/10) to extract and drop each
digit in int; or convert the int to String and use the String 's charAt() to inspect each char.

1.3 print()

Write a method called print(), which takes an int array and print its contents in the form of [a1 , a2 , . . . , an ].
Take note that there is no comma after the last element. The method's signature is as follows:

1 public static void print ( int [ ] array ) ;

Also write a test driver to test this method (you should test on empty array, one-element array, and
n-element array).
How to handle double[ ] or f loat[ ]? You need to write a overloaded version for double[ ] and a overloaded
version for f loat[ ], with the following signatures:

1 public static void p r i n t ( double [ ] array )

public static void print ( float [ ] array )

The above is known as method overloading, where the same method name can have many versions,
dierentiated by its parameter list.

Hints
1. For the rst element, print its value; for subsequent elements, print commas followed by the
value.

1.4 arrayToString()

Write a method called arrayT oString(), which takes an int array and return a String in the form of
[a1 , a2 , . . . , an ]. Take note that this method returns a String , the previous exercise returns void but
prints the output. The method's signature is as follows:

public static String arrayToString ( int [ ] array ) ;

4
HaQT Java Programming

Also write a test driver to test this method (you should test on empty array, one-element array, and
n-element array).

Notes
1. This is similar to the built-in function [Link](). You could study its source code.

1.5 contains()

Write a boolean method called contains(), which takes an array of int and an int; and returns true if
the array contains the given int. The method's signature is as follows:

1 public static boolean contains ( int [ ] array , int key ) ;

Also write a test driver to test this method.

1.6 search()

Write a method called test search(), which takes an array of int and an int; and returns the array
index if the array contains the given int; or −1 otherwise. The method's signature is as follows:

1 public static int search ( int [ ] array , int key ) ;

Also write a test driver to test this method.

1.7 equals()

Write a boolean method called equals(), which takes two arrays of int and returns true if the two arrays
are exactly the same (i.e., same length and same contents). The method's signature is as follows:

1 public static boolean equals ( int [ ] array1 , int [ ] array2 )

Also write a test driver to test this method.

1.8 copyOf()

Write a boolean method called copyOf(), which takes an int Array and returns a copy of the given
array. The method's signature is as follows:

5
HaQT Java Programming

1 public static int [ ] copyOf ( i n t [ ] array )

Also write a test driver to test this method.


Write another version for copyOf() which takes a second parameter to specify the length of the new
array. You should truncate or pad with zero so that the new array has the required length.

1 public static int [ ] copyOf ( i n t [ ] array , int newLength )

Notes
ˆ This is similar to the built-in function [Link]().

1.9 swap()

Write a method called swap(), which takes two arrays of int and swap their contents if they have the
same length. It shall return true if the contents are successfully swapped. The method's signature is
as follows:

1 public static boolean swap ( i n t [ ] array1 , int [ ] array2 )

Also write a test driver to test this method.

Notes

1 // Swap item1 and item2

int item1 ;

3 int item2 ;

int temp ;

5
temp = item1 ;

7 item1 = item2 ;

item2 = temp ;

9 // You CANNOT simply do : item1 = item2 ; item2 = item2 ;

1.10 reverse()

Write a method called reverse(), which takes an array of int and reverse its contents. For example, the
reverse of [1, 2, 3, 4] is [4, 3, 2, 1]. The method's signature is as follows:

6
HaQT Java Programming

1 public static void reverse ( int [ ] array )

Take note that the array passed into the method can be modied by the method (this is called pass by
sharing). On the other hand, primitives passed into a method cannot be modied. This is because a
clone is created and passed into the method instead of the original copy (this is called pass by value).
Also write a test driver to test this method.

Hints
1. You might use two indexes in the loop, one moving forward and one moving backward to point
to the two elements to be swapped.

1 for ( int fIdx = 0, bIdx = array . length = 1; fIdx < bIdx ; ++ f I d x , - - bIdx ) {

// Swap array [ fIdx ] and a r r a y [ bIdx ]

3 // Only need to transverse half of the array elements

2. You need to use a temporary location to swap two storage locations.

1 // Swap item1 and item2

int item1 ;

3 int item2 ;

int temp ;

5
temp = item1 ;

7 item1 = item2 ;

item2 = temp ;

9 // You CANNOT simply do : item1 = item2 ; item2 = item2 ;

1.11 GradesStatistics

Write a program called GradesStatistics, which reads in n grades (of int between 0 and 100, inclusive)
and displays the average, minimum, maximum, median and standard deviation. Display the oating-
point values upto 2 decimal places. Your output shall look like:

7
HaQT Java Programming

Command window

Enter the number of students : 4

2 Enter the grade for student 1: 50

Enter the grade for student 2: 51

4 Enter the grade for student 3: 56

Enter the grade for student 4: 53

6 The grades are : [50 , 51 , 56 , 53]

The average is : 52.50

8 The median is : 52.00

The minimum is : 50

10 The maximum is : 56

The standard deviation is : 2.29

q P
n−1
The formula for calculating standard deviation is: σ = 1
n i=0 x2i − µ2 , where µ is the mean.

Hints

1 public class GradesStatistics {

public static int [ ] grades ; // Declare an int [ ] , to be allocated later .

3 // This array is accessible by all the methods .

5 public static void main ( S t r i n g [ ] args ) {

readGrades ( ) ; // Read and save the inputs in static int [ ] grades

7 S y s t e m . o u t . p r i n t l n ( " The grades are : ") ;

print ( grades ) ;

9 S y s t e m . o u t . p r i n t l n ( " The average is " + average ( grades ) ) ;

S y s t e m . o u t . p r i n t l n ( " The median is " + median ( g r a d e s ) ) ;

11 S y s t e m . o u t . p r i n t l n ( " The minimum is " + min ( g r a d e s ) ) ;

S y s t e m . o u t . p r i n t l n ( " The maximum is " + max ( g r a d e s ) ) ;

13 S y s t e m . o u t . p r i n t l n ( " The standard deviation is " + standardDeviation ( grades ) ) ;

15
// Prompt user for the number of students and allocate the static " grades " array .

17 // Then , prompt user for grade , check for valid grade , and store in " grades ".

public static void readGrades ( ) { . . . . . . . }

19
// Print the given int array in the form of [ x1 , x2 , x3 , . . . , xn ] .

21 public static void print ( int [ ] array ) { . . . . . . . }

23 // Return the average value of the given int [ ]

public static double average ( int [ ] array ) { . . . . . . }

25
// Return the median value of the given int [ ]

27 // Median is the center element for odd=number array ,

// or average of the two center elements for even =number array .

29 // Use Arrays . s o r t ( anArray ) to sort anArray in place .

public static double median ( i n t [ ] array ) { . . . . . . }

31
// Return the maximum value of the given int [ ]

33 public static int max ( i n t [ ] array ) {

8
HaQT Java Programming

int max = array [ 0 ] ; // Assume that max is the first element

35 // From second element, if the element is more than max, set the max to this element.

. . . . . .

37 }

39 // Return the minimum value of the given int [ ]

public static int min ( i n t [ ] array ) { . . . . . . . }

41
// Return the standard deviation of the given int [ ]

43 public static double standardDeviation ( int [ ] array ) { . . . . . . . }

Take note that besides readGrade() that relies on class variable grades, all the methods are self-contained
general utilities that operate on any given array.

1.12 GradesHistogram

Write a program called GradesHistogram, which reads in n grades (as in the previous exercise), and
displays the horizontal and vertical histograms. For example:

Command window

0 = 9: ***
2 10 = 19: ***
20 = 29:
4 30 = 39:
40 = 49: *
6 50 = 59: *****
60 = 69:
8 70 = 79:
80 = 89: *
10 90 =100: **

12 *
*
14 * * *
* * * *
16 * * * * * *
0 =9 10 = 19 20 = 29 30 = 39 40 = 49 50 = 59 60 = 69 70 = 79 80 = 89 90 = 100

You might also like