You are on page 1of 4

Lab 3

Course: COSC 1047 Introduction to Computer Science II


Name: Arth Patel
Section: COSC 1047 J
Student number: 239548040
Q.
Answer:

Here, First I created triangle class that define IllegalTriangleException class, that extends the
Exception class, and it contains two constructor. After that in class Triangle I modfied second
constructor.

Code:

class IllegalTriangleException extends Exception


{
//create two constructor
public IllegalTriangleException(String message)
{
super(message);
}

public IllegalTriangleException()
{
super();
}
}

class Triangle
{
private int side1, side2, side3;
public Triangle()
{
side1 = 0;
side2 = 0;
side3 = 0;
}
//lets modified second costructor as given in the question
//second constructor
public Triangle(int side1, int side2, int side3) throws
IllegalTriangleException {
if (side1 + side2 > side3)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
else
throw new IllegalTriangleException();
}

public String toString()


{
return "Triangle [side1=" + side1 + ", side2=" + side2 + ", side3=" +
side3 + "]";
}

//TriangleTest.java

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class TriangleTest


{
public static void main(String[] args) throws IOException
{
//creates a file
File file = new File("sides.txt");
if(!file.exists())
file.createNewFile();
PrintWriter pw = new PrintWriter(file);
pw.print(getRandom()+" "+getRandom()+" "+getRandom());
pw.close();

//reading from the file


Scanner sc = new Scanner(file);
int side_1, side_2, side_3;
String data = sc.nextLine();
sc.close();
String[] ar = data.split(" ");
side_1 = Integer.parseInt(ar[0]);
side_2 = Integer.parseInt(ar[1]);
side_3 = Integer.parseInt(ar[2]);

if(side_1 > side_3)


{
int temp = side_1;
side_1 = side_3;
side_3 = temp;
}
if(side_2 > side_3)
{
int temp = side_2;
side_2 = side_3;
side_3 = temp;
}

//try, catch block


try
{
Triangle tri1 = new Triangle(side_1, side_2, side_3);
System.out.println(tri1);
}
catch(IllegalTriangleException e)
{
System.out.println(e+": The triangle cannot be created");
}
}
}

Methodology:
Here, First I created triangle class that define IllegalTriangleException class, that extends the
Exception class, and it contains two constructor. After that in class Triangle I modfied second
constructor. After that I created a test program that creates Sides.txt file. In this I use try and catch block
for handling IllegalTriangleException. In this program I made changes, that given in the question.

You might also like