Friday 25 September 2020

Java Program to handle divide by zero exception

 Exception Handling

Exceptions are the run-time errors that can be caught and handled by the programmers to avoid termination of program execution. The statements which may cause a run-time error are written inside the try block and the statements which are to be executed when an error is encountered are placed inside the catch block. A try block can be followed by more than one catch block or a finally block. The statements inside the finally block will be executed either if there is an error or no error in the program. The following program explains how to write try and catch blocks to handle exceptions. If more than one catch block follows the try block, then the catch blocks must be placed in the reverse order of the order in which the exceptions are inherited. All the exceptions both pre-defined and user-defined are the derived class of the base class Exception.


Program

import java.io.*;

class TryCatch
{
  public static void main(String[] arg)
  {
    BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
    int a,b,c;
    try
    {
        System.out.println("Enter two numbers");
        a=Integer.parseInt(x.readLine());
        b=Integer.parseInt(x.readLine());
        c=a/b;
        System.out.println("Division result = "+c);
    }
    catch(NumberFormatException e)
    {
        System.out.println("Input must be an Integer");
    }
    catch(ArithmeticException e)
    {
        System.out.println("Divide by zero error "+e);
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
  }
}


OUTPUT

D:\Java\19csc>java TryCatch
Enter two numbers
10
2
Division result = 5

D:\Java\19csc>java TryCatch
Enter two numbers
10
0
Divide by zero error java.lang.ArithmeticException: / by zero

D:\Java\19csc>java TryCatch
Enter two numbers
a
Input must be an Integer java.lang.NumberFormatException: a

Monday 14 September 2020

Java program to find the power(m, n) using user-defined function.

In Java, the Math class in java.lang package contains library functions for most of the often-used mathematical functions. Here we will write a program to find the power(m, n) which is similar to the built-in function Math.pow(m, n).


Program

import java.io.*;
//Program to find the power(m,n)
class Power
{
    public static void main(String arg[]) throws IOException
    {
        int pow=1;
        BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter two numbers x and y");
        int m=Integer.parseInt(x.readLine());
        int n=Integer.parseInt(x.readLine());
        for(int i=0;i<n;i++)
        {
          pow=pow*m;
        }
        System.out.println("Power( "+m+" , "+n+" ) = "+pow);
  }
}


OUTPUT
>java Power
Enter two numbers x and y
5
3
Power( 5 , 3 ) = 125

>java Power
Enter two numbers x and y
5
0
Power( 5 , 0 ) = 1

Sunday 13 September 2020

Java program to find the maximum in an array of integers.

In this program, the input is given as console input. Hence the readLine() function defined in the InputStreamReader class is used to get the input. The readLine() reads the input as a string which is to be converted into an integer using the Integer.parseInt() function. The BufferedReader class is used to read a stream of character from a given source ie either from a file or standard input device. Here in this program since the input is read from a standard input device (keyboard), the InputStreamReader object is initialized with System.in. All the InputStream classes are defined in the java.io package. Hence, the first line of the program must be import java.io.*; to access the classes defined in the java.io package.


Program

import java.io.*;
class Maximum
{
    public static void main(String arg[]) throws IOException
    {
        double sum=0,avg;
        int number[]=new int[20];
        int max_position=-1;
       
        BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("Enter the number of elements");
        int n=Integer.parseInt(x.readLine());
        System.out.println("Enter "+n+" numbers");
        for(int i=0;i<n;i++)
            number[i]=Integer.parseInt(x.readLine());
        
        int max=number[0];
        for(int i=0;i<n;i++)
            if (number[i]>max)
            {
                max=number[i];
                max_position=i+1;
            }
        System.out.println("The given array");
        for(int i=0;i<n;i++)
            System.out.print(number[i]+"\t");
            
        System.out.println("\nThe maximum number in the array = "+ max +" found at                                                         position = "+ max_position);
        
    }
}      

OUTPUT

>java Maximum
Enter the number of elements
5
Enter 5 numbers
4
3
9
8
1
The given array
4       3       9       8       1
The maximum number in the array = 9 found at position = 3

Java program to find the average of n numbers given as input in the command line argument.

 In Java programs, the simplest way to give input is to pass in the values along the command line while executing the program. This program finds the average of n numbers. The input given in the command line is assigned to the arg[ ] array as strings. To know the number of inputs, arg.length is used. Each element in the arg[ ] array is converted into an integer using the Integer.parseInt( ) function where Integer is a predefined wrapper class. If the input is a floating-point value then use Double.parseDouble() function to convert the command line string values to the corresponding floating-point values.

Note: The program uses the DecimalFormat class function format( ) to format the decimal output to two decimal places. This DecimalFormat class is defined in the java.text package. Hence the first line of the program imports this package.

Program

import java.text.*;
class Average
{
    public static void main(String arg[])
    {
        double sum=0,avg;
        int n=arg.length;
        DecimalFormat df = new DecimalFormat("#.##");
        for(int i=0;i<n;i++)
            sum=sum+Integer.parseInt(arg[i]);
        avg=sum/n;
        System.out.print("The average of the "+n+" numbers = ");
        System.out.println(df.format(avg));
    }
}


OUTPUT

>java Average 3 5 8 4 6 6 7 8

The average of the 8 numbers = 5.88