Sie sind auf Seite 1von 14

Abstraction / Packages / Exception Handling

Abstract Classes
1.Create an abstract class Compartment to represent a rail coach. Provide an abstract function
notice in this class. Derive FirstClass, Ladies, General, Luggage classes from the
compartment class. Override the notice function in each of them to print notice suitable to the
type of the compartment. Create a class TestCompartment. Write main function to do the
following: Declare an array of Compartment pointers of size 10. Create a compartment of a
type as decided by a randomly generated integer in the range 1 to 4. Check the polymorphic
behavior of the notice method.
Code:
abstract class Compartment
{
abstract void notice();
}
class FirstClass extends Compartment
{
void notice()
{
System.out.println("Its FIRSTCLASS");
}
}
class Ladies extends Compartment
{
void notice(){
System.out.println("Its LADIES Compartment");
}
}
class General extends Compartment
{
void notice()
{
System.out.println("Its GENERAL Compartment");
}
}
class Luggage extends Compartment
{
void notice()
{
System.out.println("Its LUGGAGE");
}
}
public class Abstract
{
public static void main(String[] args)
{
Compartment c[] = new Compartment[10];
double i = Math.random()*5;
int x = (int)i;
System.out.println(x);
switch(x)
{
case 1: c[0] = new FirstClass();
c[0].notice(); break;
case 2: c[1] = new Ladies();
c[1].notice();
break;
case 3: c[2] = new General();
c[2].notice();
break;
case 4: c[3] = new Luggage();
c[3].notice();
break;
default: System.out.println("Invalid Choice");
}
}
}
Interfaces
2. Write an interface called Playable, with a method void play(); Let this interface be placed in a
package called music. Write a class called Veena which implements Playable interface. Let this
class be placed in a package music.string Write a class called Saxophone which implements
Playable interface. Let this class be placed in a package music.wind Write another class Test in
a package called live. Then, a. Create an instance of Veena and call play() method b. Create an
instance of Saxophone and call play() method c. Place the above instances in a variable of type
Playable and then call play().

Code:
package live;
import music.Playable;
import music.string.Veena;
import music.wind.Saxophone;
public class Music {
public static void main (String[]args) {
Veena v = new Veena();
v.play();
Playable pv = new Veena();
pv.play();
Saxophone s = new Saxophone();
s.play();
Playable ps= new Saxophone();
ps.play();
}
}
package music;
public interface Playable {
void play();
}
package music.string;
import music.Playable;
public class Veena implements Playable {

public void play() {


System.out.println("Veena Plays");
}
}
package music.wind;
import music.Playable;
public class Saxophone implements Playable{
public void play() {
System.out.println("SaxophonePlays");
}
}

Exception Handling

3.Write a program that takes as input the size of the array and the elements in the
array.The program then asks the user to enter a particular index and prints the element
at that index.
This program may generate Array Index Out Of Bounds Exception. Use exception
handling mechanisms
to handle this exception. In the catch block, print the class name of the exception
thrown.

Sample Input and Output 1:


Enter the number of elements in the array
2
Enter the elements in the array
50
80
Enter the index of the array element you want to access
1
The array element at index 1= 80
The array element successfully accessed
Sample Input and Output 2:
Enter the number of elements in the array
2
Enter the elements in the array
50
80
Enter the index of the array element you want to access
6
java.lang.ArrayIndexOutOfBoundsException
Sampl
e
Input
and
Outpu
t 3:
Enter the number of elements in the array
2
Enter the elements in the array
30
j
java.lang.NumberFormatException
* */

Code:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception1{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in the arrays");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements in the array: ");
try {
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println("Enter the index of the array element you want to
access");
int index = sc.nextInt();
System.out.println("The array element at index " + index + " = " +
arr[index]);
System.out.println("The array element successfully accessed");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("java.lang.ArrayIndexOutOfBoundsException");
} catch (InputMismatchException e) {
System.out.println("java.util.InputMismatchException");
}
sc.close();
}
}

4. Write a class MathOperation which accepts integers from command line.


Create an array using these parameters. Loop through the array and obtain the sum
and
average of all the elements.
Display the result.
Check for various exceptions that may arise like ArithmeticException,
NumberFormatException, and so on.
For example: The class would be invoked as follows:
C:>java MathOperation 1900, 4560, 0, 32500

Code:
import java.util.InputMismatchException;
public class Exception2{
public static void main(String[] args) {
int n = args.length;
for (int i = 0; i < n; i++)
if (args[i].charAt(args[i].length() - 1) == ',')
args[i] = args[i].replace(",", "");
int[] arr = new int[n];
int sum = 0;
double avg = 0;
try {
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(args[i]);
for (int i = 0; i < n; i++)
sum += arr[i];
avg = sum / n;
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException");
} catch (InputMismatchException e) {
System.out.println("InputMismatchException");
}
System.out.println("sum: " + sum);
System.out.println("avg: " + avg);
}
}

5. Write a Program to take care of Number Format Exception if user enters values
other than integer for calculating average marks of 2 students. The name of the students
and marks in 3 subjects are taken from the user while executing the program.

In the same Program write your own Exception classes to take care of Negative values
and values out of range (i.e. other than in the range of 0-100)

Solution:

NegativeValuesException.java
package com.pv6;

public class NegativeValuesException extends Exception {


public NegativeValuesException() {
super();
System.out.println("NegativeValuesException occured");
}
}

ValuesOutOfRangeException.java
package com.pv6;

public class ValuesOutOfRangeException extends Exception {


public ValuesOutOfRangeException() {
super();
System.out.println("ValuesOutOfRangeException occured");
}
}

NumberException1.java
package com.pv6;

import java.util.Scanner;

public class NumberException1 {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

for (int i = 0; i < 2; i++) {


String name = "";
int subA = 0;
int subB = 0;
int subC = 0;
try {
name = sc.nextLine();

if (sc.hasNextInt())
subA = sc.nextInt();
else
throw new NumberFormatException();

if (sc.hasNextInt())
subB = sc.nextInt();
else
throw new NumberFormatException();

if (sc.hasNextInt())
subC = sc.nextInt();
else
throw new NumberFormatException();

if (subA < 0) throw new NegativeValuesException();


if (subA > 100) throw new ValuesOutOfRangeException();

if (subB < 0) throw new NegativeValuesException();


if (subB > 100) throw new ValuesOutOfRangeException();

if (subC < 0) throw new NegativeValuesException();


if (subC > 100) throw new ValuesOutOfRangeException();

}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
catch (NegativeValuesException e) {
System.out.println(e.getMessage());
}
catch (ValuesOutOfRangeException e) {
System.out.println(e.getMessage());
}

System.out.println("Name: " + name);


System.out.println("Marks of subject A: " + subA);
System.out.println("Marks of subject B: " + subB);
System.out.println("Marks of subject C: " + subC);
}

sc.close();

6. A student portal provides user to register their profile. During registration the
system needs to validate the user should be located in India. If not the system should
throw an exception.

Step 1: Create a user defined exception class named “InvalidCountryException”.


Step 2: Overload the respective constructors.
Step 3: Create a main class “UserRegistration”, add the following method,
void registerUser(String username,String userCountry) with the below
implementation
• if userCountry is not equal to “India” throw a InvalidCountryException with the
message “User Outside India cannot be registered”
• if userCountry is equal to “India”, print the message “User registration done
successfully”

Invoke the method registerUser from the main method with the data specified and see
how the program behaves.
Example1)
i/p:Mickey,US
o/p:InvalidCountryException should be thrown.
The message should be “User Outside India cannot be registered”

Example2)
i/p:Mini,India
o/p:User registration done successfully

Solution:

InvalidCountryException.java
package com.pv7;

public class InvalidCountryException extends Exception {


public InvalidCountryException() {
super();
System.out.println("InvalidCountryException occured");
System.out.println("User Outside India cannot be registered");
}
}

UserRegistration.java
package com.pv7;
public class UserRegistration {

public void registerUser(String username, String userCountry) throws


InvalidCountryException {
if (!userCountry.equals("India"))
throw new InvalidCountryException();
else
System.out.println("User registration done successfully");

public static void main(String[] args) {

UserRegistration registration = new UserRegistration();

try {
registration.registerUser("Mickey", "US");

}
catch (InvalidCountryException e) {

}
}

7. Write a program to accept name and age of a person from the command
prompt(passed as arguments when you execute the class) and ensure that the age
entered is >=18 and < 60.
Display proper error messages.
The program must exit gracefully after displaying the error message in case the
arguments passed are not proper.

(Hint : Create a user defined exception class for handling errors.)

Solution:
InvalidAgeException.java
package com.pv8;

public class InvalidAgeException extends Exception {


public InvalidAgeException() {
super();
System.out.println("Invalid age");
}
}

Age.java
package com.pv8;

public class Age {

public static void main(String[] args) throws InvalidAgeException {


String name = args[0];

int age = Integer.parseInt(args[1]);

if (age < 18 || age >= 60)


throw new InvalidAgeException();

System.out.println("Name: " + name + " Age: " + age);


}
}

Das könnte Ihnen auch gefallen