Results 1 to 2 of 2
  1. #1
    black_fender is offline Member
    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Default Impose conditions to method parameters

    I have the main method that starts like this
    Java Code:
    public static void main(String[] args) { 
    //parameter evaluation
    byte TheDigit = Byte.parseByte(args[0]);
    }
    I want to impose a condition to args[0] to be just a digit. I want to be able to display a WARN message if the value is not just a digit ( such as "-2" "99" "2,3" "word" etc). I want to avoid all those situations by displaying a warn message and exit the program. All this before the compiler shows me any error.
    For example if the method will be given the parameter "1.3" I dont want to let the compiler to display the error "java.lang.NumberFormatException: For input string: "1.3"
    I want to evaluate the parameter before that.
    In order to do that I have tried to create the variable this way :
    Java Code:
    byte TheDigit = (byte)args[0]
    by casting a byte variable from the input parameter but it does not work because args[0] is a string.
    Also I tried to parse the parameter as an integer and then to impose it the condition to be >= 0 and <= 9
    Java Code:
     int TheDigit = Integer.parseInt(args[1]);
    But it doesn't work if I give it "1.3" parameter because Integer.parseInt gives me the error "java.lang.NumberFormatException: For input string: "1.3" .

    Any ideas how to avoid all that ?

    Thanks

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default Re: Impose conditions to method parameters

    Java Code:
    if(args[0] == null || args[0].length() != 1 || !Character.isDigit(args[0].charAt(0))){
    	System.out.println("ERROR!");
    }
    ???
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

Similar Threads

  1. Replies: 2
    Last Post: 08-10-2012, 03:40 PM
  2. objects as parameters change in method
    By zcd in forum New To Java
    Replies: 0
    Last Post: 01-29-2012, 09:37 PM
  3. Replies: 5
    Last Post: 11-21-2010, 03:08 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •