Consider the following class D. There are three spaces where code needs to be co
ID: 3548195 • Letter: C
Question
Consider the following class D. There are three spaces where code needs to be completed. Please label each piece of code with the corresponding problem number.
public class D
{
private int number;
private String text;
public D(int n, String txt)
{
setNum(n);
setText(txt);
}
public D(D obj)
{
number = obj.number;
text = obj.text;
}
public setNum(int n)
{
number = n;
//1. Throw an exception if n is negative
}
public setText(String txt)
{
text = txt;
//2. Throw an exception if txt is empty.
}
public String toString()
{
return "The object value: " + number + " and " + text;
}
}
//3. Create a main method that demonstrates the use of class D and is capable of handling exception handling.
Explanation / Answer
Hi, Please find the program below. The Main function constructs two D Objects for incorrect and correct input. The methods throws the exception and the constructor catches it and displays the message, hence the object values are not intialized when the exception occurs. PFB. public class D { private int number; private String text; public D(int n, String txt) { try { setNum(n); } catch (Exception e) { System.out .println("Exception Occurred The number entered is negative"); } try { setText(txt); } catch (Exception e) { System.out.println("Exception Occurred The text entered is empty"); } } public D(D obj) { number = obj.number; text = obj.text; } public void setNum(int n) throws Exception { // 1. Throw an exception if n is negative if (n < 0) throw new Exception(); number = n; } public void setText(String txt) throws Exception { // 2. Throw an exception if txt is empty. if (txt == null || txt.equalsIgnoreCase("")) throw new Exception(); text = txt; } public String toString() { return "The object value: " + number + " and " + text; } // 3. Create a main method that demonstrates the use of class D and is // capable // of handling exception handling. public static void main(String[] args) { D d = new D(-1, ""); System.out.println(d.toString()); D d1 = new D(1, "hi"); System.out.println(d1.toString()); } } Output: Exception Occurred The number entered is negative Exception Occurred The text entered is empty The object value: 0 and null The object value: 1 and hi Hope it helps. Thanks, SriRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.