Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taking even number from user and giving exception error if number is odd

Tags:

java

exception

I am a java student and I am writing a java program with exception handling. In this program, I am trying to write a program that gets 5 even number from user and if the user enter odd number then show an exception that the number is odd. I am using custom exception "oddexception" in this program.

Now let's talk about the issue. So I have an issue that this program isn't compiling. It show an error which is mentioned in the image below.

The answer to this question can be small and stupid for you but I am a beginner in java so this answer really matters for me. please help me.

Please help me to find a solution. The solution

import java.lang.Exception;
class oddexception extends Exception
{
    oddexception(String message, int a)
    {   
        System.out.println(message);
        System.out.println("Invalid Number is/are "+a);
    }
}
class program4
{
    public static void main(String args[])
    {
        Integer n[] = new Integer[5];
        int j=0;
        for(int i=0; i<5; i++)
        {
            try
            {
                n[i] = Integer.valueOf(args[i]);
                if(n[i]%2!=0)
                {
                    j++;
                    throw new oddexception("Number is odd "+n[i]);
                }
            }
            catch(oddexception e)
            {
                System.out.println("Caught my exception");
            }
        }
        System.out.println("Invalid numbers are : "+j);
    }
}   

enter image description here

like image 229
Abhishek Diwakar Avatar asked Dec 05 '25 04:12

Abhishek Diwakar


2 Answers

From the error message it quite clear that the constructor of your exception is expecting a String and an integer (oddexception(String message, int a)). Where as you just passing a String.

throw new oddexception("Number is odd "+n[i]); //results to String

So changing a bit of your code

  throw new oddexception("Number is odd " , n[i]);
like image 119
Suresh Atta Avatar answered Dec 07 '25 18:12

Suresh Atta


Your oddexception constructor has two arguments, so instead of

throw new oddexception("Number is odd "+n[i]);

you should write

throw new oddexception("Number is odd ",n[i]);
like image 33
Eran Avatar answered Dec 07 '25 18:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!