Showing posts with label exceptions. Show all posts
Showing posts with label exceptions. Show all posts

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

Dividing a Number in Java with Exception Handling

Description:

In this java code, we show you how to handle Exceptions when you divide two numbers by each other.

Code:

package com.javaproblems.divisionbyzerowithe;

import java.util.InputMismatchException;
import java.util.Scanner;

public class DivisionByZeroE {

 private static int ratio(int num, int denom) {
  return num/denom;
 }

public static void main(String[] args) {
 int numerator, denominator, result;
 @SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
 boolean continueLoop = true;
 do {
  try { 
  System.out.println("Please enter numerator: ");
  numerator = scan.nextInt();
  System.out.println("Please enter denominator: ");
  denominator = scan.nextInt();
    
  result = ratio(numerator, denominator);
  System.out.println(result);
  continueLoop = false;
  }
                catch(InputMismatchException e) {
    System.out.println("Exception: " + e);
    scan.nextLine();
  System.out.println("You must enter an int value."
                                    + " Please try again");
   } catch (ArithmeticException e) {
   System.out.println("Exception: " + e.getMessage());
   System.out.println("Zero is not a valid value. + " +
      " Please try again");
   }
   
   
  } while(continueLoop);
  
  
 }
}
 
Read More

Creating an OutOfRangeException in Java

Description:

In this java code, we create an OutOfRangeException; and then we test it.

Code:

package com.javaproblems.creatingexceptions;

import java.util.Scanner;

public class CreatingExceptions {

 public static void main(String[] args) throws OutOfRangeException {
  Scanner scan = new Scanner(System.in);
  int val;
  final int MIN = 0, MAX = 100;
  OutOfRangeException problem = 
  new OutOfRangeException("Input value is not valid");
  System.out.println("Enter an int value between " +
                          MIN + " and " + MAX);
  val = scan.nextInt();
 
  if (val<MIN || val > MAX) {
   throw problem;
  }

 }

}
package com.javaproblems.creatingexceptions;

public class OutOfRangeException extends Exception{

 
 public OutOfRangeException(String msg) {
  super(msg);
  
 }

}
Read More

Difference between Checked and Unchecked exceptions in Java

Java distinguishes between checked exceptions and unchecked exceptions. This distinction is important, because the Java compiler enforces a catch-or-declare requirement for checked exceptions. An exception’s type determines whether it’s checked or unchecked. All exception types that are direct or indirect subclasses of class RuntimeException (package java.lang) are unchecked exceptions. These are typically caused by defects in your program’s code. Examples of unchecked exceptions include ArrayIndexOutOfBoundsExceptions (discussed in Chapter 7) and ArithmeticExceptions (shown in Fig. 11.3). All classes that inherit from class Exception but not class RuntimeException are considered to be checked exceptions. Such exceptions are typically caused by conditions that are not under the control of the program — for example, in file processing, the program can’t open a file because the file does not exist. Classes that inherit from class Error are considered to be unchecked.

The compiler checks each method call and method declaration to determine whether
the method throws checked exceptions. If so, the compiler verifies that the checked exception is caught or is declared in a throws clause. We show how to catch and declare checked exceptions in the next several examples. Recall from Section 11.3 that the throws clause specifies the exceptions a method throws. Such exceptions are not caught in the method’s body. To satisfy the catch part of the catch-or-declare requirement, the code that generates the exception must be wrapped in a try block and must provide a catch handler for the checked-exception type (or one of its superclass types). To satisfy the declare part of the catch-or-declare requirement, the method containing the code that generates the exception must provide a throws clause containing the checked-exception type after its parameter list and before its method body. If the catch-or-declare requirement is not satisfied, the compiler will issue an error message indicating that the exception must be caught or declared. This forces you to think about the problems that may occur when a method that throws checked exceptions is called.

Unlike checked exceptions, the Java compiler does not check the code to determine

whether an unchecked exception is caught or declared. Unchecked exceptions typically can be prevented by proper coding. For example, the unchecked ArithmeticException exception can be avoided if the method ensures that the denominator is not zero before attempting to perform the division. Unchecked exceptions are not required to be listed in a method’s throws clause—even if they are, it’s not required that such exceptions be caught by an application.
Read More

How to Create your Own Exception in Java

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}
Methods that can potentially throw or propagate this exception must declare it:
public void calculate(int i) throws FooException, IOException;
... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}
You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).
Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}
Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}
Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.
The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.
Read More

Creating a Product Code Validator in Java

Problem:

Write a program that asks the user to enter a product code starting with the form of: NNNNL, where N denotes a number and L a letter. Keep asking the user for a product number until the user enters "XXX". If N > 2000 and L = B, the code is blacklisted and considered as banned.

The main point of this product validator is to be able to handle exceptions in a robust manner. Thus, you are expected to handle two exceptions manually: IndexOutOfBoundsException and NumberFormatException.

At the end of the program, print the total number of attempts, valid codes and banned codes.


Output:

Enter a product code (XXX to quit):
1900G
Enter a product code (XXX to quit):
2500B
Enter a product code (XXX to quit):
1000R
Enter a product code (XXX to quit):
190G
Code of improper length.
Enter a product code (XXX to quit):
190RG
Region is not numeric.
Enter a product code (XXX to quit):
XXX
Total # attempts: 5
# valid codes: 3
# banned codes: 1


Solution:

import java.util.Scanner;
 public class ProductCodes {
     public static void main(String[] args)
     {    
         String code;
         Scanner scan = new Scanner(System.in);
         char city;
         int region, valid = 0, banned = 0,total = 0;
          
         System.out.println("Enter a product code (XXX to quit): ");
         code = scan.nextLine();
          
         while (!code.equals("XXX"))
         {
         try {
             total++;
             city = code.charAt(4);
             region = Integer.parseInt(code.substring(0,4));
             valid++;
             if (city == 'B' && region >= 2000)
                 banned++;
         } catch (StringIndexOutOfBoundsException e) {
             System.out.println("Code of improper length.");
         } catch (NumberFormatException e ) {
             System.out.println("Region is not numeric.");
         } finally {
              
         }
         System.out.println("Enter a product code (XXX to quit): ");
         code = scan.nextLine();
     }
         System.out.println("Total # attempts: " + total);
         System.out.println(" # valid codes: " + valid);
         System.out.println(" # banned codes: " + banned);
     }        
 }
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