Showing posts with label interface. Show all posts
Showing posts with label interface. Show all posts

Translate ADT into java interface example 4

Problem:

Translate this ADT into a Java interface:
ADT: Polynomial
degree(): int
derivative(): Polynomial
equals(Point): Boolean
sum(Polynomial): Polynomial
toString(): String
valueAt(Real): Real

Output:

None

Solution:

public interface Polynomial {
 public int degree();
 public Polynomial derivative();
 public boolean equals(Object object);
 public Polynomial sum(Polynomial polynomial);
 public String toString();
 public double valueAt(double x);
}
Read More

Translate ADT into java interface example 3

Problem:

Translate this ADT into a Java interface:
ADT: Circle
area(): Real
center(): Point
circumference(): Real
contains(Point): Boolean
equals(Circle): Boolean
radius(): Real
toString(): String

Output:

None

Solution:

public interface Circle {
 public double area();
 public Point center();
 public double circumference();
 public boolean contains(Point point);
 public boolean equals(Object object);
 public double radius();
 public String toString();
}
Read More

Translate ADT into a Java interface Example 2

Problem:

Translate this ADT into a Java interface:
ADT: Line
contains(Point): Boolean
equals(Line): Boolean
isHorizontal(): Boolean
isVertical(): Boolean
slope(): Real
toString(): String
xIntercept(): Real
yIntercept(): Real

Output:

None.

Solution:

public interface Line {
 public boolean contains(Point point);
 public boolean equals(Object object);
 public boolean isHorizontal();
 public boolean isVertical();
 public double slope();
 public String toString();
 public double xIntercept();
 public double yIntercept();
}
Read More

Translate ADT into Java Interface Example

Problem:

Translate this ADT into a Java interface:
ADT: Point
amplitude(): Real
distanceTo(Point): Real
equals(Point): Boolean
magnitude(): Real
toString(): String
xCoordinate(): Real
yCoordinate(): Real

Output:

None

Solution:

public interface Point {
 public double amplitude();
 public double distanceTo(Point point);
 public boolean equals(Object object);
 public double magnitude();
 public String toString();
 public double xCoordinate();
 public double yCoordinate();
}
Read More

Creating an Exception Application in Java

Problem:

RegistrationCheck

+ registerStudent(student : Student, courseId : int) : void

Student
- id : long
- name : String
- coursesFinished : Course[]
+ Student(id : long, name : String, coursesFinished : Course[])
+ setId(id : long) : void
+ getId() : long
+ setName(name : String) : void
+ getName(): String
+ setCoursesFinished(coursesFinished : Course[]) : void
+ getCoursesFinished() : Course[]
+ toString() : String

Course
- id : int
- name : String
- preRequisite : Course
+ Course(id : int, name : String, preRequisites: Course[])
+ setId(id : int) : void
+ getId() : int
+ setName(name : String) : void
+ getName(): String
+ setPreRequisite(preRequisite: Course) : void
+ getPreRequisite() : Course
+ toString() : String



RegistrationCheckSystem
- courses : Course[]
+ registerStudent(student : Student, courseId : int) : void

RegistrationException

+ RegistrationException(message : String)

CourseNotFoundException

+ CourseNotFoundException(message : String)

In this assignment, you will be creating a Course Registration Checking System which will check if a student can register a course or not.
First, you have an interface which is the Registration interface that has one method declaration. The method is registerStudent which takes a student and a course ID as parameters.
The class Student has three private variables which are id, name, and courses finished. These variables should be initialized in the constructor and should have set and get methods.
The Course class has three private variables which are id, name, and pre-requisites. These variables should be initialized in the constructor and should have set and get methods.
The RegistrationSystem class has an array of courses and should implement the registration interface. This means that this class should implement the registerStudent method. The class has an array of available courses.
The registerStudent method should check if the student can register a specific course. The method checks if the student has finished the pre-requisites of a specific course. If so, the methods should print that the student can register this course. If the student has not completed the pre-requisites, a RegistrationException should be thrown. If the course that the student wants to register is not found, a CourseNotFoundException should be thrown.
The CourseNotFoundExceptionclass should extends the Java Exception class and call the superclass’ constructor in its constructor.
The RegistrationException class should extends the Java Exception class and call the superclass’ constructor in its constructor.
Write a tester class that creates a student and checks if a student can register a course. For simplicity, limit the number of courses to five courses.
Input should be read from the user via a scanner. First read the user id, name, and the courses he or she has finished. The number of finished courses should be two courses only.
Then read an integer which will be the course id of the course that the student wants to register. Then call resgiterStudent passing the student and the course id as a parameter.
There are a number of exceptions that should be handled in the tester class.
InpuMissmatchException might be thrown if the user enters invalid input. If so, you should tell the user that her or his input is wrong and keep requesting to enter a valid input.
The other exception is CourseNotFoundException that will be thrown if the user enters a course id that is not found. You should handle this exception by keeping on requesting from the user to enter a valid course id.
RegistrationException will be thrown if the student has not completed the prerequisites of the course. This should be handled by printing that the student cannot register this course.
Hints:
-          Use a while loop to keep requesting valid input from the user.
-          Use the following table as a course description:

id
name
preRequisite
10
CSC243
-
11
CSC245
CSC243
12
CSC310
CSC245
13
MTH201
-
14
MTH202
MTH201

Output:

Student id: 20110515
Student name: Test Student
Courses finished: 10 13
Course to register: test
Please enter a valid input!
Course to register: 12

Student has not completed the course prerequisites

Solution:

/**--------------------Course.java-----------------*/
public class Course
{
 private int id;
 private String name;
 private Course preRequisite;
 
 
 public Course(int id, String name, Course preRequisite) {
  this.id = id;
  this.name = name;
  this.preRequisite = preRequisite;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Course getPreRequisite() {
  return preRequisite;
 }
 public void setPreRequisite(Course preRequisite) {
  this.preRequisite = preRequisite;
 }
 
 public String  toString()
 {
  
 }
 
}
/**------------CourseNotFoundException.java-----------*/
public class CourseNotFoundException extends Exception
{
 public CourseNotFoundException()
 {
  super();
 }
 public CourseNotFoundException(String message)
 {
  super(message);
 }
}
/**------------RegistrationCheck.java--------------*/
public interface RegistrationCheck
{
 void registerStudent(Student student,int courseId) 
     throws RegistrationException, CourseNotFoundException;
}
/**------------RegistrationCheckSystem.java--------*/
public class RegistrationCheckSystem implements RegistrationCheck
{
 private Course[] courses;
 public void registerStudent(Student student, int courseId)
   throws RegistrationException, CourseNotFoundException {
  courses = new Course[5];
  courses[0] = new Course(10, "CSC243", null);
  courses[1] = new Course(11, "CSC245", courses[0]);
  courses[2] = new Course(12, "CSC310", courses[1]);
  courses[3] = new Course(13, "MTH201", null);
  courses[4] = new Course(14, "MTH202", courses[3]);

  int targetCourse = -1;
  boolean preRequisiteCompleted = false;
  for (int i=0;i 14) throw new CourseNotFoundException();
   coursesFinished[0] = new Course(i,null,null);
   int j = scan.nextInt();
   if (j<10 data-blogger-escaped-j="">14) throw new CourseNotFoundException();
   coursesFinished[1] = new Course(i,null,null);
   keepLooping = false;
   }
   
   catch (InputMismatchException inputMismatchException)
   {
    scan.nextLine();
    System.err.println("Exception: " + inputMismatchException);
    System.out.println("Please enter a valid input!");
   }
   
   catch(CourseNotFoundException courseNotFoundException)
   {
    System.err.println("Exception: " + courseNotFoundException);
    System.out.println("Course does not exist");
   }
     
   keepLooping = true;
   while(keepLooping)
   {
    try
    {
     System.out.print("Course to register: ");
     int courseId = scan.nextInt();
     RegistrationCheckSystem registrationCheckSystem = new RegistrationCheckSystem();
     registrationCheckSystem.registerStudent(new Student(id,name, coursesFinished),courseId);
     keepLooping =false;
    }
   
   
   catch (InputMismatchException inputMismatchException)
   {
    scan.nextLine();
    System.err.println("Exception: " + inputMismatchException);
    System.out.println("Please enter a valid input!");
   }
   
   catch(CourseNotFoundException courseNotFoundException)
   {
    System.err.println("Exception: " + courseNotFoundException);
    System.out.println("Course does not exist");
   }
   catch(RegistrationException registrationException)
   {
    System.err.println("Execption: " + registrationException);
    System.out.println("Student has not completed the course prerequisites");
   }
   }
  }
 }
}
Read More

Creating an Exception Application in Java

Problem:

Reservation

+ reserveSeat(seatNumber : int) : void
+ reserveSeats(seatN umbers : int[]) : void
+ cancelReservation(seatNumber : int) : void
+ cancelReservations(seatNumbers : int[]) : void


MovieReservation
- seats : int[]        
+ MovieReservation(seats : int[])
+ reserveSeat(seatNumber : int) : void
+ reserveSeats(seatN umbers : int[]) : void
 + cancelReservation(seatNumber : int) : void
+ cancelReservations(seatNumbers : int[]) : void
 + toString() : String

TravelTicketReservation

- seats : int[]
+ TravelTicketReservation(seats : int[])
+ reserveSeat(seatN umber : int) : void
+ reserveSeats(seatN umbers : int[]) : void
+ cancelReservation(seatNumber : int) : void
+ cancelReservations(seatNumbers : int[]) : void
 + toString() : String

SeatException

+ SeatException(message : String)



In this lab, you will be creating a Movie Reservation System and a Travel Ticket Reservation that will implement an interface, and a SeatException class.

The Reservation interface has five methods that need to be implemented which are reserveSeat, reserveSeats, cancelReservation, and cancelReservations.

The SeatException class will extend the Java Exception class. Its constructor will take a string as a parameter and call the superclass' constructor passing the string to it as a parameter.

The MovieReservation class and the TravelTicketReservation class will implement the interface's methods. They also have a private variable which is an array of integers representing the seats. The constructor should initialize this variable.

The reserveSeat method will take an integer named seatNumber as a parameter and sets seats[seatNumber] to one indicating that the seat is reserved. If the seat is already reserved, a SeatException should be thrown.

The reserveSeats method will take an integer array named seatNumbers as a parameter and sets all the seat numbers in the array to one indicating that the seat is reserved. If the seat is already reserved, a SeatException should be thrown.

The cancelReservation method will take an integer named seatNumber as a parameter and sets seat[seatNumber] to zero indicating that the seat is empty. If the seat is already empty, a SeatException should be thrown.

The cancelReservations method will take an integer array named seatNumbers as a parameter and sets all the seat numbers in the array to zero indicating that the seat is empty. If the seat is already empty, a SeatException should be thrown.

You should write a tester class that will have an instance of MovieReservation and TravelTicketReservation and then call the previous methods. You should use try and catch blocks to handle the exceptions that might be thrown in these methods.

For each instance, the tester class should read input from the user by using a scanner. For simplicity, make the number of seats ten. First, the user must enter ten numbers which are either zero or one, so use a for loop to read ten numbers and set the value of seats[i] to the read value.

Then, read an int value from the user and call reserveSeat passing the value as a parameter. Then, read four int values from the user and call reserveSeats passing the values as a parameter. Then do the same thing for cancelReservation and cancelReservations.

There are three types of exceptions that can happen when calling these functions. The first one is a SeatException as discussed earlier. The second one is an IndexOutOfBoundsException which will occur if the user enters a number that is less than zero or greater that seats.length. The third one is an InputMismatchException if the user enters a value which is not an integer.


After each call to the functions, you should print the seats array, or print "Seat number does not exist" if an IndexOutOfBoundsException occurs, or "Seat already reserved or empty" if a SeatException occurs, or "Input should be an Integer" if an InputMismatchException occurs.

Solution:

/**------------------Reservation.java--------------*/
public interface Reservation {
 
 public void reserveSeat(int seatNumber) throws SeatException;
 public void reserveSeats(int seatNumbers[]) throws SeatException;
 public void cancelReservation(int seatNumber) throws SeatException;
 public void cancelReservations(int seatNumbers[]) throws SeatException;
 
}

/**------------------MovieReservation.java---------*/
public class MovieReservation implements Reservation {

 private int seats[];
 
 public MovieReservation(int seats[]) {
  this.seats = seats;
 }
 
 @Override
 public void reserveSeat(int seatNumber) throws SeatException {
  if (seats[seatNumber] == 1)
   throw new SeatException("Seat already reserved");
  else
   seats[seatNumber] = 1;
 }

 @Override
 public void reserveSeats(int[] seatNumbers) throws SeatException {
  
  for (int i = 0; i < seatNumbers.length; i++) {
   if (seats[seatNumbers[i]] == 1)
    throw new SeatException("Seat already reserved");
   else
    seats[seatNumbers[i]] = 1;
  }
 }

 @Override
 public void cancelReservation(int seatNumber) throws SeatException {
  if (seats[seatNumber] == 0)
   throw new SeatException("Seat already empty");
  else
   seats[seatNumber] = 0;
 }

 @Override
 public void cancelReservations(int[] seatNumbers) throws SeatException {

  for (int i = 0; i < seatNumbers.length; i++) {
   if (seats[seatNumbers[i]] == 0)
    throw new SeatException("Seat already empty");
   else
    seats[seatNumbers[i]] = 0;
  }
 }

 public String toString() {
  return "";
 }
}

/**-------------TravelTicketReservation.java-------*/
public class TravelTicketReservation implements Reservation {

private int seats[];
 
 public TravelTicketReservation(int seats[]) {
  this.seats = seats;
 }
 
 @Override
 public void reserveSeat(int seatNumber) throws SeatException {
  if (seats[seatNumber] == 1)
   throw new SeatException("Seat already reserved");
  else
   seats[seatNumber] = 1;
 }

 @Override
 public void reserveSeats(int[] seatNumbers) throws SeatException {
  
  for (int i = 0; i < seatNumbers.length; i++) {
   if (seats[seatNumbers[i]] == 1)
    throw new SeatException("Seat already reserved");
   else
    seats[seatNumbers[i]] = 1;
  }
 }

 @Override
 public void cancelReservation(int seatNumber) throws SeatException {
  if (seats[seatNumber] == 0)
   throw new SeatException("Seat already empty");
  else
   seats[seatNumber] = 0;
 }

 @Override
 public void cancelReservations(int[] seatNumbers) throws SeatException {

  for (int i = 0; i < seatNumbers.length; i++) {
   if (seats[seatNumbers[i]] == 0)
    throw new SeatException("Seat already empty");
   else
    seats[seatNumbers[i]] = 0;
  }
 }

 public String toString() {
  return "";
 }
}

/**------------------SeatException.java------------*/
public class SeatException extends Exception {
 //simple
 public SeatException(String message) {
  super(message);
 }
 
}

/**------------------Tester.java-------------------*/
import java.util.InputMismatchException;
import java.util.Scanner;

public class Tester {

 public static void main(String[] args) {
  
  Scanner scan = new Scanner(System.in);
  
  int seats[] = new int[10];
  
  System.out.print("Please initialize seats: ");
  
  for (int i = 0; i < seats.length; i++)
   seats[i] = scan.nextInt();
  
  MovieReservation movieReservation = new MovieReservation(seats);
  
  try {
   System.out.print("Enter a seat number to reserve: ");
   int seatNumber = scan.nextInt();
   
   movieReservation.reserveSeat(seatNumber);
   System.out.println("Seat reserved successfully");
   
   /**-------------------------------------------*/
   
   System.out.println("Enter four seats to reserve: ");
   int seatNumbers[] = new int[4];
   
   for (int i = 0; i < seatNumbers.length; i++)
    seatNumbers[i] = scan.nextInt();
   
   movieReservation.reserveSeats(seatNumbers);
   System.out.println("Seats reserved successfully");
   
   /**-------------------------------------------*/
   
   System.out.print("Enter a seat number to cancel: ");
   seatNumber = scan.nextInt();
   
   movieReservation.cancelReservation(seatNumber);
   System.out.println("Seat cancelled successfully");
   
   /**-------------------------------------------*/
   
   System.out.println("Enter four seats to cancel: ");
   seatNumbers = new int[4];
   
   for (int i = 0; i < seatNumbers.length; i++)
    seatNumbers[i] = scan.nextInt();
   
   movieReservation.cancelReservations(seatNumbers);
   System.out.println("Seats cancelled successfully");
   
  } catch (SeatException e) {
   System.out.println("Error: could not reserve or cancel seat");
  } catch (ArrayIndexOutOfBoundsException e) {
   System.out.println("Error: entered number must be greater than -1 and less than 10");
  } catch (InputMismatchException e) {
   System.out.println("Error: entered value must be a number");
  }
  
  scan.close();
 }

}
Read More

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact