CSC1109_Tutorials/Week8_Lab/CircleWithException.java

58 lines
1.6 KiB
Java

package Week8_Lab;
import java.util.Scanner;
public class CircleWithException {
private double radius;
public CircleWithException(double radius) throws IllegalArgumentException {
if (radius < 0) {
throw new IllegalArgumentException("Radius cannot be negative");
}
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) throws IllegalArgumentException {
if (radius < 0) {
throw new IllegalArgumentException("Radius cannot be negative");
}
this.radius = radius;
}
public double getArea() throws Exception{
double area = Math.PI * radius * radius;
if (area > 1000){
throw new Exception("Area cannot be greater than 1000");
}
return area;
}
// Exceptions not stated in Lab Instructions
public double getDiameter() {
return radius * 2;
}
public static void main(String[] args) {
CircleWithException c1 = new CircleWithException(5);
Scanner sc = new Scanner(System.in);
System.out.print("Enter a radius: ");
double radius = sc.nextDouble();
try {
CircleWithException c2 = new CircleWithException(radius);
System.out.println("Radius: " + c2.getRadius());
System.out.println("Area: " + c2.getArea());
System.out.println("Diameter: " + c2.getDiameter());
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}