Q.Write a java program to accept a number from a user, if it is zero then throw user defined Exception “Number is Zero”. If it is non-numeric then generate an error “Number is Invalid” otherwise check whether it is palindrome or not. [15 M]
import java.util.Scanner;
// User-defined Exception
class ZeroNumberException extends Exception
{
public ZeroNumberException(String msg)
{
super(msg);
}
}
public class PalindromeCheck
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
try
{
System.out.print("Enter a number: ");
String input = sc.nextLine();
int num = Integer.parseInt(input); // may throw NumberFormatException
if(num == 0)
{
throw new ZeroNumberException("Number is Zero");
}
int original = num;
int rev = 0;
while(num > 0)
{
int rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
if(original == rev)
System.out.println("Number is Palindrome");
else
System.out.println("Number is Not Palindrome");
}
catch(NumberFormatException e)
{
System.out.println("Number is Invalid");
}
catch(ZeroNumberException e)
{
System.out.println(e.getMessage());
}
sc.close();
}
}