Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: check for valid argument to a method

  1. #1
    Junior Member
    Join Date
    Mar 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default check for valid argument to a method

    Hi,

    I am a newbie and have just managed to make my first java program wokr I am now taking that program further to enable it do some error handling with throw -> try -> catch

    I want the called method to handle the detection and calling method to handle the error. My problem is to write the proper syntax in java to check if the passed argument to called methods parameter is indeed a integer or not and then throw an exception. Here is the code that I have created:

    import java.io.*;
    import java.util.Scanner;
     
    public class root {
     
    	public static int calcRoot(int a)
    	{
    		 if (a != integer) //what is the proper syntax to check if the parameter is a integer?
    		throw new intErrorExecption("Input must be a integer");
    		return a=(int) Math.sqrt(a);
    	}
     
     
    	public static void main(String[] args) throws IOException 
    	{
    		int tempInt=0;
     
    		String sCont;
    		BufferedReader stdin = new BufferedReader
    			      (new InputStreamReader(System.in));
    		try{
     
    		do 
    		{
     
    		System.out.print("Enter integer: ");
    		System.out.flush();
    		tempInt=Integer.parseInt( stdin.readLine());
     
    		}  
     
    	       catch (intErrorExecption e)
    	       {System.out.println("ERROR: Only a integer is a valid input");
    		 } 
     
     
    	       System.out.println("The square root of " +tempInt+ " is "+calcRoot(tempInt));
     
     
     
    	       System.out.print("Do you want to continue? (y / n): ");
     
     
    	       System.out.flush();
     
     
    			/* Code to check if the read line provided y or n, if y continue loop else
    			 *  exit loop and print "Thank you for participating"
    			 */
     
    			sCont=stdin.readLine();
    			 if(sCont.equals("n"))
    			    {
    			    	break;
     
    			    }
     
    			} while	(sCont.equals("y"));
     
     
     
    		System.out.println("Thank you for participating");
     
     
    	}
     
    }

    Thanks,
    -Sohail


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: check for valid argument to a method

    By definition...
    public static int calcRoot(int a)

    ....a is an Integer. I'm not sure what you wish to check...do you wish to check if it is positive (for instance, the Math.sqrt of a negative number is NaN)

  3. #3
    Junior Member
    Join Date
    Mar 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: check for valid argument to a method

    Actually I just want to check that the value passed to this methods argument is a integer at all? If not, I want the method to throw a exception and the the calling method to catch it handle it.

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: check for valid argument to a method

    That does not make sense. Given you have defined the method as such, if you attempt to pass anything other than an int you will get a compile time error. Thus there is no reason to deal with this at runtime.

  5. #5
    Junior Member
    Join Date
    Mar 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: check for valid argument to a method

    The point is more of a usability issue, I dont wont the user be presented by a compile time error, I want it gracefully handled. I want the user to be able to pass on whatever and then be presented by a error that makes sense.

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: check for valid argument to a method

    Quote Originally Posted by lupis View Post
    The point is more of a usability issue, I dont wont the user be presented by a compile time error, I want it gracefully handled. I want the user to be able to pass on whatever and then be presented by a error that makes sense.
    You should read the definitions of compile time and runtime error. Compile time occurs when you compile your application, and in the most basic sense NEVER seen by a user.

    Compile Time Error:
    public static int calcRoot(int a){
        return (int)Math.sqrt(a);
    }
     
    public static void main(String[] args){
        System.out.println(calcRoot("1"));//compile time error - this program won't even compile, let alone run
    }

    Runtime 'Error'

    public static int calcRoot(int a){
        if ( a < 0 ){
            throw new IllegalArgumentException("Cannot calculate the square root of a negative number");//runtime
        }
        return (int)Math.sqrt(a);
    }
     
    public static void main(String[] args){
        System.out.println(calcRoot(-1));
    }

    Perhaps reading the basic of methods might help:
    http://docs.oracle.com/javase/tutori...O/methods.html

  7. #7
    Junior Member
    Join Date
    Mar 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: check for valid argument to a method

    I do see your point. If i comment out the if statement in my method and all the throw and try catch codes, I have no problems running the program as long as I feed it with integers, but if I submit a string value generates :

    Enter integer: s
    Exception in thread "main" java.lang.NumberFormatException: For input string: "s"
    at java.lang.NumberFormatException.forInputString(Unk nown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at root.main(root.java:28)

    Is there anyway to catch this input and check it for a integer, if not then reply with a message that the input has to be a integer

  8. #8
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: check for valid argument to a method

    I have no problems running the program as long as I feed it with integers, but if I submit a string value generates :
    Yes, don't feed Strings. The Integer class has a parseInt method that allows you to parse a String into an int, and it will throw a NumberFormatException if the String cannot be parsed into an int, allowing you to catch the exception and deal with it accordingly.

  9. #9
    Member
    Join Date
    Jan 2012
    Location
    Hyderabad, Andhra Pradesh, India
    Posts
    32
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: check for valid argument to a method

    I think that I have understood what you require. But before that let me point out that your do doesn't have an associated while.

    If all that you wish to do is to print an appropriate message when the user enters an invalid integer, then you can catch the exception in the try catch block which will be automatically thrown by the calcRoot method. Your calcRoot method need not check if it is a String. If during run time, a String is passed instead of a number an exception will be generated automatically. So your code can simply be:

    public static int calcRoot(int a)
    	{
     
    		return a=(int) Math.sqrt(a);
    	}

    In the main method you need to catch the exception as it might be generated by the calcRoot function. This is how your code structure needs tolook like:

    public static void main(String[] args)
    {
    // accept value from user
    try
    {
    // call calcSqrt function here and add whatever you want
    }
    catch(NumberFormatException e)
    {
    // process error by displaying an appriate message or do anything else that you want to do
    }
    }

Similar Threads

  1. Java Program to Check whether a Expression is Valid using Stack
    By rainbow9 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 12th, 2011, 02:11 AM
  2. How to remove argument from abstract method.
    By jainshasha in forum Object Oriented Programming
    Replies: 12
    Last Post: June 30th, 2011, 10:33 PM
  3. [SOLVED] Send File (path) as argument to method
    By efluvio in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 31st, 2011, 01:13 PM
  4. Valid toString method?
    By dcshoecousa in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 4th, 2010, 11:55 AM
  5. Generic method using an int[] argument
    By dubois.ford in forum Collections and Generics
    Replies: 2
    Last Post: March 18th, 2010, 07:18 AM