Data Structures and Algorithm: Object Oriented Design: Example 1: Circle
Problem: Create a program that would ask the user for the radius of a circle then display its area and circumference.
CLASS: Circle, TestProgCircle
// Circle.java -------------------------------------------------------------
public class Circle {
private double rad;
private double a;
private double c;
public Circle(){ //default constructor
rad = 0;
}
public Circle(double r){ //constructor with parameters
rad = r;
}
public Circle(Circle other){ //copy constructor
rad = other.rad;
}
public String toString(){
String str;
a = 3.1416 * rad * rad;
c = 3.1416 * 2 * rad;
str = "The area is " + a + " and the circumference is " + c;
return str;
}
}
// end of Circle.java -----------------------------------------------------
// TestProgCircle.java ----------------------------------------------------
import java.io.*;
import java.util.*;
public class TestProgCircle {
public static void main(String [] args) throws IOException{
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
double no;
System.out.print("Enter a radius: ");
no = Double.parseDouble(keyboard.readLine());
Circle c1 = new Circle(no);
System.out.println("C1: " + c1);
}
}
// end of TestProgCircle.java ---------------------------------------------
No comments:
Post a Comment