Java Reference
In-Depth Information
public class
Test {
public static void
main(String[] args) {
// Initialize times
int
times =
3
;
System.out.println(
"Before the call,"
+
" variable times is "
+ times);
public class
Test {
public static void
main(String[] args) {
int
i =
0
;
while
(i <=
4
) {
method1(i);
i++;
}
// Invoke nPrintln and display times
nPrintln(
"Welcome to Java!"
, times);
System.out.println(
"After the call,"
+
" variable times is "
+ times);
}
System.out.println(
"i is "
+ i);
}
public static void
method1(int i) {
do
{
if
(i %
3
!=
0
)
System.out.print(i +
" "
);
i--;
}
while
(i >=
1
);
// Print the message n times
public static void
nPrintln(
String message,
int
n) {
while
(n >
0
) {
System.out.println(
"n = "
+ n);
System.out.println(message);
n--;
}
}
}
System.out.println();
}
}
(c)
(d)
6.14
For (a) in the preceding question, show the contents of the activation records in the
call stack just before the method
max
is invoked, just as
max
is entered, just before
max
is returned, and right after
max
is returned.
Modularizing makes the code easy to maintain and debug and enables the code to be
reused.
Key
Point
Methods can be used to reduce redundant code and enable code reuse. Methods can also be
used to modularize code and improve the quality of the program.
Listing 5.9 gives a program that prompts the user to enter two integers and displays
their greatest common divisor. You can rewrite the program using a method, as shown in
ListingĀ 6.6.
VideoNote
Modularize code
L
ISTING
6.6
GreatestCommonDivisorMethod.java
1
import
java.util.Scanner;
2
3
public class
GreatestCommonDivisorMethod {
4
/** Main method */
5
public static void
main(String[] args) {
6
// Create a Scanner
7 Scanner input =
new
Scanner(System.in);
8
9
// Prompt the user to enter two integers
10 System.out.print(
"Enter first integer: "
);
11
int
n1 = input.nextInt();
12 System.out.print(
"Enter second integer: "
);
13
int
n2 = input.nextInt();
14
Search WWH ::
Custom Search