Sunday, 12 March 2023

5. Write a Java program to input n integer numbers and display lowest and second lowest number. Also handle the different exceptions possible to be thrown during execution.

 


import java.util.*;

class Program5
{
    public static void main(String args[])
    {
        try
        {
            System.out.println("how many numbers you want to enter: ");
            Scanner sc = new Scanner(System.in);
            int no = sc.nextInt();
           
            int arr[] = new int[no];
           
            System.out.println("\nenter number one by one: ");
            for(int i=0; i<arr.length; i++)
            {
                arr[i] = sc.nextInt();
            }
           
            int temp;
            for(int i=0; i<arr.length; i++)
            {
                for(int j=0; j<arr.length; j++)
                {
                    if(arr[i] < arr[j])
                    {
                        temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
           
            System.out.println("\nlowest number: " + arr[0] + "\nsecond lowwest: "
+ arr[1]);
        }
        catch(ArithmeticException e)
        {
            System.out.println("Arithmatic exception occured");
        }
        catch(ArrayIndexOutOfBoundsException a)
        {
            System.out.println("ArrayIndexOutOfBoundsException");
        }
        catch(NumberFormatException n)
        {
            System.out.println("NumberFormatException please enter only a numbers");
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}


No comments:

Post a Comment

python programs

1. sum of two number