Java_CH8_Solutions
Java_CH8_Solutions
1. (Rectangle Class) Create a class Rectangle with attributes length and width, each of which
defaults to 1. Provide methods that calculate the rectangle’s perimeter and area. It has set and get
methods for both length and width. Theset methods should verify that length and width are each
floating-point numbers larger than 0.0 and less than 20.0. Write a program to test class Rectangle.
Solution:
public class Rectangle {
private double length;
private double width;
// constructor
public Rectangle(){
setLength(1.0f);
setWidth(1.0f);
}
public Rectangle(double length, double width){
setLength(length);
setWidth(width);
}
public void setLength(double length){
if(length >= 0.0f && length <=20.0f)
this.length = length;
else
throw new IllegalArgumentException("length must be between 0.0 and 20.0");
}
public void setWidth(double width){
if(width >= 0 && width <= 20)
this.width = width;
else
throw new IllegalArgumentException("width must be between 0.0 and 20.0");
}
public double getLength(){
return this.length;
}
public double getWidth(){
return this.width;
}
// calculate perimeter
public double getPerimeter(){
return (length * 2) + (width * 2);
}
// calculate area
public double getArea(){
return length * width;
}//end getArea
return s;
}//end toString
}//end class
2. Write an enum type TrafficLight, whose constants (RED, GREEN, YELLOW) take one parameter
—the durationof the light. Write aprogram to test the TrafficLight enum sothat it displaysthe enum
constants and their durations.
Solution:
public enum TrafficLight{
RED(24),
GREEN(40),
YELLOW(5);
// instance field
private final int duration;
// constructor
TrafficLight(int duration){
2
this.duration = duration;
}
// accessor for duration
public int getDuration(){
return this.duration;
}
}//end class
3. Write a program to display a date with two formats: DD/MM/YYYY and Month Name
DD/YYYY. Create a Date class with a constructor that has three parameters: day, month and year.
The program should check for the invalid values of day, month and year when initializing the date.
Solution:
package CH_8;
//DateTest.java
import java.util.Scanner;
public class DateTest{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
}
}
Output:
Date: 06/26/1998
Date with month name: June 26/1998