Professional Documents
Culture Documents
Semester II 2014/2015
Lab 3: You will learn how to create Java programs that we have seen in the lecture
Instruction:
Submit Question 1 by next weeks lab through Moodle. You should submit a word document that
contains java code and screenshot of your output. Name your .doc as Exercise2.doc or Exercise2.docx
Exercise 1:
1. Create a new project, name it Lab3.
2. Create a new class name Ch3Circle.
3. The code for the class should as follows:
//Chapter 3 Sample Program: Compute Area and Circumference
class Ch3Circle {
public static void main( String[] args ) {
final double PI = 3.14159;
double radius, area, circumference;
radius = 2.35;
//compute the area and circumference
area
= PI * radius * radius;
circumference = 2.0 * PI * radius;
System.out.println("Given Radius: " + radius);
System.out.println("Area: " + area);
System.out.println("Circumference: " + circumference);
}
}
4. Compile, run the class and observe the output. The output should be in the default format
Exercise 2:
3. Compile, run and observe the output. The output now are formatted according to the specified
format (3 decimal values)
*/
import java.text.*;
class Ch3Circle3 {
public static void main( String[] args )
3. Compile, run and observe the output. Now the output is properly aligned.
Note: You may use the escape sequence as well to indicate tab and new line (\t and \n)
Exercise 4:
3. Compile, run and observe the output. This program uses input from user and displays the result
in specified format to the console window.
Exercise 5
/*
Chapter 3 Sample Program: Estimate the Pole Height
*/
import java.text.*;
import java.util.*;
class Ch3PoleHeight {
public static void main( String[] args ) {
double
double
double
double
double
double
height;
distance;
alpha;
beta;
alphaRad;
betaRad;
//try 23
3. Compile, run and observe the output. In this exercise, you use the standard Math class to
convert degree to radian.
Note: To use methods in Math class, you dont need to create an object because all methods in
class Math are static.
4. You also use DecimalFormat class to format your output
Exercise 6
GregorianCalendar cal;
SimpleDateFormat sdf;
Scanner scanner = new Scanner(System.in);
System.out.print("Year (yyyy): ");
year
= scanner.nextInt();
System.out.print("Month (1-12): ");
month
= scanner.nextInt();
System.out.print("Day (1-31): ");
day
= scanner.nextInt();
cal = new GregorianCalendar(year, month-1, day);
sdf = new SimpleDateFormat("EEEE");
System.out.println("");
System.out.println("Day of Week: " + sdf.format(cal.getTime()));
}
}