In: Computer Science
Write a class called Pen that contains the following information:
public class Pen {
Here is the solution,
// your code starts here
import java.util.Scanner;
public class Pen
{
// instance variables - replace the example below with your
own
private float price;
private String color;
// constructor with two arguments/parameters
public Pen(float price , String color)
{
try {
if(price < 0)
throw new IllegalArgumentException("Price cannot be
negative");
this.price = price;
this.color = color;
}
catch(IllegalArgumentException e) {
System.out.println(e);
}
}
// for getting price
// no need for exception since we will never allow negative
number
// for the object
public float getPrice()
{
return this.price;
}
// for getting color
// exception handling is not for color
public float getColor()
{
return this.price;
}
// setting price, over here we again have to check for negative
numbers
// so we have the Exceptional handling
(IllegalArgumentException)
public void setPrice(float price)
{
try {
if(price < 0)
throw new IllegalArgumentException("Price cannot be
negative");
this.price = price;
}
catch(IllegalArgumentException e) {
System.out.println(e);
}
}
// to set color. No exception handling to be done for color.
public void setColor(String color)
{
this.color = color;
}
// main/driver
public static void main(String[] args) {
// trying to create object with negative number
// exception will be thrown here
Pen a = new Pen(-2,"blue");
// creating object
Pen b = new Pen(2,"black");
// trying to set value with negative number
// exception will be thrown here
b.setPrice(-9);
}
}
//code ends here
here is the sample output:-
hhere is the screenshot of the code for proper understanding.
Thank You.