- Question 1
- What is the output of the following program segment?
int k, j=2, m=3;
for (k=0; k<=m; k++)
System.out.println("k= "+ k);
j += 3*k;
System.out.println("j= "+ j);
- Question 2
- Write a program segment that reads a non-negative integer
n and outputs a triangle with n ASCII
characters on each side. The n lines of the triangle
alternately contains asterisks (*) and question marks (?). E.g.,
if the input is 5, the following pattern should be printed:
*
??
***
????
*****
- Question 3
- Experiment with classes Interval and
Person developed in lecture: (1) write more "client code" to
learn to call methods, (2) add more methods to Interval and/or
Person.
- Question 4
- Fill in the blanks to complete classes Sphere and
Calculation below. Class Calculation is the
client of Sphere. Read through both incomplete classes before
you start writing. It may be helpful to complete class
Sphere before class Calculation. Pay attention
to the comments.
public class Calculation {
public static void main(String[] args) {
// create two Sphere objects
________________ ball = ________________________(4.0,"ball");
________________ orange = ________________________(4.0,"orange");
// compute volume of the ball
________________ ballVol = ________________________;
// print a description of the orange
___________________________________________________;
} //method main
} //class Calculation
public class Sphere {
____________ double radius; // radius of sphere
____________ ____________ type; // what the sphere is
// Constructor: assign values to the two instance variables of the Sphere
____________ ____________(____________ r, ____________ t) {
____________________________________________________________________
| |
| |
| |
|____________________________________________________________________|
} //constructor
// instance method getVolume for calculating volume of the Sphere
____________________________________________________________________
| |
| |
| |
| |
|____________________________________________________________________|
// define a toString method for showing the type and radius of the Sphere
____________________________________________________________________
| |
| |
| |
| |
|____________________________________________________________________|
} //class Sphere
- Question 5
- Does the following "swap" operation work? What is the output?
/* Try to swap two values */
public class SwapValues {
public static void main(String[] args){
int x= 9;
int y= 2;
System.out.println("x=" + x + ", y=" + y);
swap(x,y);
System.out.println("x=" + x + ", y=" + y);
}
public static void swap(int x, int y) {
int tmp;
tmp= x;
x= y;
y= tmp;
}
} //class SwapValues