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

I have observed carefully your code . It is perfectly fine for handling the above mentioned exception and the logic for providing correct number of instances is also correct . The issue is with the TesterCircle class inside the try block . Fisrt statement for creating object i.e new CircleWithException(0); this will not throw any error and simple change the value of numberOfObject variable 0 to 1

Your second statement new CircleWithException(-5); This will throw an exception as this is negative radius and hence the value of numberOfObject variable will not change , it will remain 1 only.

Now , your third statement new CircleWithException(5); , this will not get executed ever as the statement above this new CircleWithException(-5) , has thrown an exception . Hence this will not get execute ever and will the numberOfObject will be 1 only .. That is why , it is showing the value 1 always.

Reason is , when any exception is thrown then the complier ignores all the statement below that statement where the exception was thrown and control get passed to the catch block .

if you change the order of your statements

CircleWithException c1 = new CircleWithException(0);
CircleWithException c3 = new CircleWithException(-5);
CircleWithException c2 = new CircleWithException(5);

to

CircleWithException c1 = new CircleWithException(0);
CircleWithException c3 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);

then your code will work fine and will show output as 2 which is the correct expected answer.

Below is the image for cross testing


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