DESCRIPTION:
5 even numbers from command line & If any of the number is odd then throw custom exception OddException and Count Invalid Numbers.
CODING:
5 even numbers from command line & If any of the number is odd then throw custom exception OddException and Count Invalid Numbers.
CODING:
import java.util.*; // To use Scanner & InputMismatchException Class
class OddEven
{
public static void main(String[] args)
{
Scanner num=new Scanner(System.in);
int invalid_num=0;
String s;
try
{
for(int i=0;i<5;i++)
{
System.out.print("Input Even Number : ");
s=num.nextLine();
if((int)(s.charAt(0))<48 || (int)(s.charAt(0))>57)
{
invalid_num++;
}
else
{
if(Integer.parseInt(s)%2!=0)
{
System.out.println("Number Of Invalid Number:"+invalid_num);
throw new OddException();> //Also Define throw new OddException(String s);
}
}
}
}
catch(OddException Ex)
{
System.out.print("Error : " + Ex.getMessage());
}
catch(InputMismatchException e)
{
System.out.print("Error : Input Numeric Value 0 to 9...");
}
System.out.println("Number Of Invalid Number:"+invalid_num);
}
}
class OddException extends Exception
{
OddException()
{
super("Input Only Even Number!");
}
OddException(String msg) //When Throw with Argument like throw new OddException(String s);
{
super(msg);
}
}
class OddEven
{
public static void main(String[] args)
{
Scanner num=new Scanner(System.in);
int invalid_num=0;
String s;
try
{
for(int i=0;i<5;i++)
{
System.out.print("Input Even Number : ");
s=num.nextLine();
if((int)(s.charAt(0))<48 || (int)(s.charAt(0))>57)
{
invalid_num++;
}
else
{
if(Integer.parseInt(s)%2!=0)
{
System.out.println("Number Of Invalid Number:"+invalid_num);
throw new OddException();> //Also Define throw new OddException(String s);
}
}
}
}
catch(OddException Ex)
{
System.out.print("Error : " + Ex.getMessage());
}
catch(InputMismatchException e)
{
System.out.print("Error : Input Numeric Value 0 to 9...");
}
System.out.println("Number Of Invalid Number:"+invalid_num);
}
}
class OddException extends Exception
{
OddException()
{
super("Input Only Even Number!");
}
OddException(String msg) //When Throw with Argument like throw new OddException(String s);
{
super(msg);
}
}
Comments
Post a Comment