Question

In: Computer Science

Revise this code to handle exceptions and provide correct total number of valid objects. (1) /**...

Revise this code to handle exceptions and provide correct total number of valid objects.

(1)

/**
 * class: CircleWithException
 * description: This program creates CircleWithException specification by using an instance variable/data/attribute named
 * radius.
 * Then, also we will create a static variable named numberOfObjects to count number of object when you create in a tester program.
 * In this program, you will learn how you declare an exception and define the exception.
 * This is a part of checked exception process.
 * Regarding the checked exception, besides run time error exceptions, all other exceptions declared must be checked when
 * a caller calls the method with a checked exception.
 */
public class CircleWithException {
    private double radius;

    private static int numberOfObject = 0;

    //1
    public CircleWithException(){
        this(1.0);
    }

    //2
    public CircleWithException(double rad){
        //this.radius = rad;
        setRadius(rad);
        numberOfObject++;
    }

    public double getRadius() {
        return radius;
    }


    /**
     * method: setRadius
     * @param radius
     * @throws IllegalArgumentException
     *
     * description: setRadius method throws an exception if the radius is negative.
     * this case, this method will throw an IllegalArgumentException.
     * throws   is the keyword to indicate that this method throw this type of exception.
     * the caller must MUST MUST handle the exception using a try-catch block or we put "throws any exception from
     * the main method.
     * We can throw either checked or unchecked exceptions.
     *
     * The keyword throws will allow the compiler to help you write a code to handle this type of error.
     * BUT it does not prevent the abnormal termination of the problem.  With the help of the throws keyword,
     *  you can provide the information to the caller of the method about the type of the exceptions the method might throw.
     */
    public void setRadius(double radius) throws IllegalArgumentException { //declare the IllegalArgumentException

        if(radius >= 0)
        this.radius = radius;

        else
            throw new IllegalArgumentException("Radius cannot be a negative number. ");
    }
    //eureka
    public static int getNumberOfObject() {
        return numberOfObject;
    }

    //if you see static then it is a class method. a class method is also called a static method.
    //static method is called by the classname when it is called outside of the class which defined that method.
    //inside of CircleWithException, you call getNumberOfObject()
    //outside of CircleWithException, you call getNumberOfObject by using this format:  CircleWithException.getNumberOfObject()
    //if you do not include static, then it is an instance method. it is also called non-static method.
    //with an example of area method, if you create an object name c1, then you call area() by the object named c1.
    //c1.area()


    public double area() {
        return radius * radius * Math.PI;
    }
}


(2)
 
public class TesterCircle {

    public static void main(String[] args) {
        try {
            CircleWithException c1 = new CircleWithException(0);
            CircleWithException c3 = new CircleWithException(-5);
            CircleWithException c2 = new CircleWithException(5);

        }
        catch(IllegalArgumentException e){
            System.out.println(e);
        }
        System.out.println("Number of Objects created: " + CircleWithException.getNumberOfObject());//
    }
}

Solutions

Expert Solution

If you clearly analyze and dry-run the code, what happens is when we construct first object, c1 with parameter as 0, since this parameter satisfies the condition for drawing a circle on a plane so increment the count to 1(Since numberOfObjects is a static member, so it will be available for all objects).

Now, when we try to construct the second object c2 with value as -5, is violates our condition and our setRadius method throws the Exception as "Radius cannot be a negative number."

As per the rule of try-catch, when exception is thrown, the program just terminates and passes control to catch block, where you can use the exception to notify the user about the problem. And just after its execution, the control goes out of catch and continues the normal execution.

Hence , Total no. of objects created will be 1 only, because after trying to constructing c2, the excution flowed to catch block and then the System.out.println() statement.

So on the Console you will see output as -->

java.lang.IllegalArgumentException: Radius cannot be a negative number. 
Number of Objects created: 1

Exception due to negative argument and received by catch block where it is printed and then normal print statement executed to check no. of objects created.


Related Solutions

Revise this code to handle exceptions and provide correct total number of valid objects. (1) /**...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /** * class: CircleWithException * description: This program creates CircleWithException specification by using an instance variable/data/attribute named * radius. * Then, also we will create a static variable named numberOfObjects to count number of object when you create in a tester program. * In this program, you will learn how you declare an exception and define the exception. * This is a part of checked...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /**...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /** * class: CircleWithException * description: This program creates CircleWithException specification by using an instance variable/data/attribute named * radius. * Then, also we will create a static variable named numberOfObjects to count number of object when you create in a tester program. * In this program, you will learn how you declare an exception and define the exception. * This is a part of checked...
Is 100202345X a valid ISBN number? If not, what would the correct check digit have to...
Is 100202345X a valid ISBN number? If not, what would the correct check digit have to be ? Solve the congruence 121x ≡ 5 mod 350.
how to code in c# to get the total number of 1's as the numbers are...
how to code in c# to get the total number of 1's as the numbers are added in a Listbox in windows forms
C++ CODE PLEASE MAKE SURE TO USE STRINGSTREAM AND THAT THE OUTPUT NUMBER ARE CORRECT 1....
C++ CODE PLEASE MAKE SURE TO USE STRINGSTREAM AND THAT THE OUTPUT NUMBER ARE CORRECT 1. You must call all of the defined functions above in your code. You may not change function names, parameters, or return types. 2. You must use a switch statement to check the user's menu option choice. 3. You may create additional functions in addition to the required functions listed above if you would like. 4. If user provides option which is not a choice...
a) write a python programme for converting url.to html please provide valid code and please share...
a) write a python programme for converting url.to html please provide valid code and please share screenshots to me
Provide the Java code to compute the sum, average, maximum number and minimum number if I...
Provide the Java code to compute the sum, average, maximum number and minimum number if I have a string sentence of double numbers. Assume that the length of the string sentence is not known. It can be of any length. To split a string based on the comma character use the following. String sentence = "A,B,C,D,E"; String[] stringsArray = receivedSentence.split(","); Then stringsArray is an array of five elements such that: stringsArray[0] = 'A' stringsArray[1] = 'B' stringsArray[2] = 'C' stringsArray[3]...
1. Assume you are writing code to serialize a group of Student objects to an XML...
1. Assume you are writing code to serialize a group of Student objects to an XML document. What Java API method will you call to execute the serialization process? NOTE: You must use the XML serialization/deserialization method/concepts presented in this course. 2. Assume that the list of exception types below may occur within the scope of a method. In order to properly handle these exceptions, each type must be handled individually and separately.  Arrange the exception types in the order in...
Intro to java Problem, Please provide code and Pseudocode. Not able to compile correct numbers. Problem...
Intro to java Problem, Please provide code and Pseudocode. Not able to compile correct numbers. Problem 7: Simple Calculator (10 points) (General) Calculators represent the most basic, general-purpose of computing machines. Your task is to reduce your highly capable computer down into a simple calculator. You will have to parse a given mathematical expression, and display its result. Your calculator must support addition (+), subtraction (-), multiplication (*), division (/), modulus(%), and exponentiation (**). Facts ● Mathematical expressions in the...
Intro to Java Question. Please Provide code and pseudocode for understanding. Not receiving correct results currently....
Intro to Java Question. Please Provide code and pseudocode for understanding. Not receiving correct results currently. Problem 5: Player Move Dungeon (10 points) (Game Development) You're the lead programmer at a AAA studio making a sequel to the big hit game, Zeldar 2. You've been challenged to implement player movement in dungeons. The game is top-down, with dungeons modeled as a 2d grid with walls at the edges. The player's location is tracked by x,y values correlating to its row...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT