Javalab - 7 Methods: Final Double PI 3.14159
Javalab - 7 Methods: Final Double PI 3.14159
JavaLab_7
LAB
METHODS
%Lab7_1:
For example, you can declare PI as a constant as follows program to compute the area of a circle.
public class ComputeArea {
// Declare a constant
public static void main(String[] args)
{
double radius = 20;
// Assign a radius
ComputeArea Obj = new ComputeArea();
double area = Obj.MyArea(radius) ; // call object method MyArea
System.out.println("The area for the circle of radius " +radius + " is " + area);
}
double MyArea(double R)
{ // not static
return R*R*PI;
}
}
%Lab7_2:
This program tests two methods: the boolean method isLeapYear ( ) and the void method test ( ).
public class TestLeapYear{
public static void main(String[] args){
test (1492) ;
test (1592) ;
test (1600) ;
test (1700) ;
test (1776) ;
test (1992) ;
test (1999) ;
test ( 2000 ) ;
}
static boolean isLeapYear(int n){
// should be static
if (n < 1582)
return false;
if (n%400 == 0)
return true;
if (n%100 == 0)
------------------------------------------------------------------------------------------------------------------------------------------------Dr Mohammed Fadhl
[] J A V A
LAB
return false;
if (n%4 == 0)
return true;
return false;
}
static void test(int n){
// should be static
if ( isLeapYear(n) )
System.out.println(n + is a leap near.");
else
System.out.println(n + is not a leap near.");
}
}
%Lab7_3:
Write and run a Java program that generates a random integer and reports whether it is divisible
by 2, by 3, or by 5. Hint: n is divisible by d if the remainder from dividing n by d is 0.
import java.util.Random;
public class TestDivisibility{
public static void main(String[] args){
Random random = new Random( ) ;
int n = random.nextInt();
System.out.println("n= + n);
Check(n) ;
}
static void Check(int n ){
if (n%2 == 0)
System.out.println("n is divisible by 2") ;
if (n%3 == 0)
System.out.println("n is divisible by 3 " ) ;
if (n%5 == 0)
System.out.println("n is divisible by 5");
}
}
[] J A V A
LAB
%Lab7_4:
Sort the array a[] in ascending order using an insertion sort.
class Some {
void sort(int a[]) {
for (i=0; i< a.length;i++) {
for(j=0; j<a.length-1; j++)
} // for
} // method
} // class
public class MY {
public static void main (String[] args)
//new int[5]
%Lab7_5:
[] J A V A
LAB