Tuesday, May 21, 2013

Object Oriented Programming - Exception handling


 Write a java source code of a program with following features:  

1) A class StudentNames that manages a String array of names of the 20 students. Include following methods: a. void addName(String name)  :  add names to the array b. void deleteName(String name) :  delete names from the array based on name c. void deleteName(int id)  :  delete names from the array based on index d. boolean search(String name)  :  search a name e. void addName(String name, int index): add name to an index   
2) Two user defined exceptions IndexNotAvailableException and IndexOutOfRangeException as subclasses of the java Exception class. Throw an IndexNotAvailableException if a name exists in the location. Throw an IndexOutOfRangeException if an index is out of range (index < 0 || index > 20) 


public class StudentsName {

    String [] names ;
    int index;
    public StudentsName() {
        names = new String[20];
        index = 0;
    }
   
    void addName(String name) throws IndexOutOfBoundsException{
       
        if(index >= 20){
            throw new IndexOutOfBoundsException();
        }else{
            names[index] = name;
            index ++;
        }
   
    }
   
    void deleteByName(String name){
        for(int i=0;i<20;i++){
            if(names[i].equals(name)){
                names[i]="";
                break;
            }
        }
   
    }
   
    void deleteByIndex(int id)throws  IndexOutOfRange{
        if(id <0 || id >=20){
        throw new IndexOutOfRange();
        }else{
            names[id]="";
        }
   
    }
   
    boolean search(String name){
     for(int i=0;i<20;i++){
            if(names[i].equals(name)){
               return true;
            }
        }
        return false;
    }
   
    void addname(String name , int index) throws IndexOutOfRange, IndexNotAvailable{
        if(index < 0 || index >= 0){
            throw  new IndexOutOfRange();
        }else if(!names[index].isEmpty()){
            throw  new IndexNotAvailable();
        }else{
       
        }
    }
     
}



class IndexNotAvailable extends Exception{

    public IndexNotAvailable() {
        System.out.println("Entered index is not available !!");
    }
   

}

class IndexOutOfRange extends Exception{

    public IndexOutOfRange() {
        System.out.println("Entered index is not in range !!");
    }


}

No comments:

Post a Comment