Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Tutorial #6

1. What is the output of the following unknown method?


public class Strange {
public static final int MAX = 5;
public static void main(String[] args) {
unknown();
}
public static void unknown() {
int number = 0;
for (int count = MAX; count >= 1; count——) {
number += (count * count);
}
System.out.println("The result is: " + number);
}
}

2. Suppose that you are trying to write a program that produces the following output:

1 3 5 7 9 11 13 15 17 19 21
1 3 5 7 9 11

The following program is an attempt at a solution, but it contains four major errors. Identify them all.
public class BadNews {
public static final int MAX_ODD = 21;

public static void writeOdds() {


// print each odd number
for (int count = 1; count <= (MAX_ODD - 2); count++) {
System.out.print(count + " ");
count = count + 2;
}

// print the last odd number


System.out.print(count + 2);
}

public static void main(String[] args) {


// write all odds up to 21
writeOdds();

// now, write all odds up to 11


MAX_ODD = 11;
writeOdds();
}
}

1 of 2
3. Suppose that you have a variable called line that will take on the values 1, 2, 3, 4, and so on, and a class
constant named SIZE that takes one of two values. You are going to formulate expressions in terms of
line and SIZE that will yield different sequences of numbers of characters. Fill in the table below,
indicating an expression that will generate each sequence.

line value Constant SIZE value Number of characters Expression


1, 2, 3, 4, 5, … 1 4, 6, 8, 10, 12, … (line + SIZE) * 2
2 6, 8, 10, 12, 14, …
1, 2, 3, 4, 5, … 3 13, 17, 21, 25, …
5 19, 23, 27, 31, …
1, 2, 3, 4, 5, … 4 10, 9, 8, 7, 6, …
9 20, 19, 18, 17, …

4. Write a Java program that generates the following output. Use static methods to show structure and
eliminate redundancy in your solution.

5. Write a java program that prints the following output. Use static methods and use nested for loops to
print the repeated parts of the figure. Once you get it to work, add a class constant so that the size of the
figure can be changed simply by changing the constant’s value.

+===+===+
| | |
| | |
| | |
+===+===+
| | |
| | |
| | |
+===+===+

2 of 2

You might also like