Display lowest and second lowest number & handle the different exceptions possible to be thrown during execution in JAVA.
LOGIC 1: Use Sort Method
CODING:
CODING:
LOGIC 1: Use Sort Method
CODING:
import java.util.*;
class lowest
{
public static void main(String[] args)
{
Scanner num=new Scanner(System.in);
try
{
System.out.print("How Many Numbers want to Input:");
int[] arry=new int[num.nextInt()];
for(int i=0;i<arry.length;i++)
{
System.out.print("Input A Number:");
arry[i]=num.nextInt();
}
Arrays.sort(arry);
System.out.println("Lowest Number : " + arry[0] + "\nSecond Lowest Number : " + arry[1]);
}
catch(InputMismatchException e1)
{
System.out.print("Error::Input only Numeric Value");
}
}
}
LOGIC 2:Without use Sort Method,time complexity of logic 2 less than logic 1,because each data is sorting in logic 1class lowest
{
public static void main(String[] args)
{
Scanner num=new Scanner(System.in);
try
{
System.out.print("How Many Numbers want to Input:");
int[] arry=new int[num.nextInt()];
for(int i=0;i<arry.length;i++)
{
System.out.print("Input A Number:");
arry[i]=num.nextInt();
}
Arrays.sort(arry);
System.out.println("Lowest Number : " + arry[0] + "\nSecond Lowest Number : " + arry[1]);
}
catch(InputMismatchException e1)
{
System.out.print("Error::Input only Numeric Value");
}
}
}
CODING:
import javax.swing.JOptionPane; //To Use Input Dialog Box
import java.util.*; //To use NumberFormatException Class
class lowest
{
public static void main(String[] args)
{
String num=JOptionPane.showInputDialog(null, "Enter Number...");
int lowest=Integer.parseInt(num),Slowest=Integer.parseInt(num);
try
{
for(int i=0;i<n;i++)//'n' means how many numbers user input
{
num=JOptionPane.showInputDialog(null, "Enter Number...");
if(Integer.parseInt(num)!=lowest && Integer.parseInt(num)!=Slowest)
{
if(lowest>Integer.parseInt(num))
{
Slowest=lowest;
lowest=Integer.parseInt(num);
}
else
{
if(Slowest>Integer.parseInt(num) || Slowest==lowest)
Slowest=Integer.parseInt(num);
}
}
}
}
catch(NumberFormatException e)
{
System.out.print("Error::Input Numeric Value...");
}
System.out.println("Lowest Number : " + lowest + "\nSecond Lowest Number : " + Slowest);
}
}
import java.util.*; //To use NumberFormatException Class
class lowest
{
public static void main(String[] args)
{
String num=JOptionPane.showInputDialog(null, "Enter Number...");
int lowest=Integer.parseInt(num),Slowest=Integer.parseInt(num);
try
{
for(int i=0;i<n;i++)//'n' means how many numbers user input
{
num=JOptionPane.showInputDialog(null, "Enter Number...");
if(Integer.parseInt(num)!=lowest && Integer.parseInt(num)!=Slowest)
{
if(lowest>Integer.parseInt(num))
{
Slowest=lowest;
lowest=Integer.parseInt(num);
}
else
{
if(Slowest>Integer.parseInt(num) || Slowest==lowest)
Slowest=Integer.parseInt(num);
}
}
}
}
catch(NumberFormatException e)
{
System.out.print("Error::Input Numeric Value...");
}
System.out.println("Lowest Number : " + lowest + "\nSecond Lowest Number : " + Slowest);
}
}
Comments
Post a Comment