Results 1 to 20 of 20
  1. #1
    itaipee is offline Member
    Join Date
    Dec 2008
    Posts
    99
    Rep Power
    0

    Default method that return 2 arguments

    hi ,

    I need to make methods that check errors in input. I want them to return 2 things : boolean for if the check passed. and string for telling what the error is .

    How to do it ?

    Java Code:
    //what I want 
    String str=null;
    if (checkErrorMethod(str)==true)
          System.out.println("this is the error :"+str);

  2. #2
    dswastik is offline Senior Member
    Join Date
    Dec 2008
    Location
    Kolkata
    Posts
    282
    Rep Power
    6

    Default

    A method can never return more than one value, so considering you scenario you can think of returning a collection, here is a sample code

    import java.util.*;
    class A{

    public static List getStatusAndMessage(String str){
    ArrayList <Object>al=new ArrayList<Object>();
    if(str==null){
    al.add(new Boolean(false));
    al.add("String is null");
    }
    else{
    al.add(new Boolean(true));
    al.add("Valid string");
    }
    return al;
    }


    public static void main(String args[]){
    String str=null;
    ArrayList al=(ArrayList)getStatusAndMessage(str);
    Boolean b=(Boolean)al.get(0);
    boolean flag=b.booleanValue();
    if(!flag){
    System.out.println(al.get(1));
    }
    }
    }

  3. #3
    MuslimCoder is offline Senior Member
    Join Date
    Jan 2009
    Posts
    119
    Rep Power
    0

    Default

    Hello,

    I am not sure if that is possible, Allah knows best. I think you should use a seperate class e.g ErrorChecker then Create variables, which you can access.

  4. #4
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Yes, List is the best option you have to do this. If you want to return the same data type in multiple times, you can use an array as well.

  5. #5
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default

    This time I disagree with you.
    If you use a Collection you must:
    • to wrap the bool in a Boolean object
    • declare it as a List<Object>, then specifying the type of the returned object with a cast, without taking advantage of generic types.

    I think you could simply return a String object and either
    • throw an exception
    • OR returning null

    So your code may look like:
    Java Code:
    try {
       ...
       String error = myChecker.checkError();
       System.out.println("Error found: " + error);
       ...
    } catch (NoErrorFoundException e) {
       System.out.println("No errors found");
    }
    Or (which I think is the best):
    Java Code:
    // Note that the checkError() method must return
    // a descriptive String if an error is found and a null
    // object otherwise.
    String error = myChecker.checkError(strToTest);
    if ( error != null ) {
       System.out.println("Error found: " + error);
    } else {
       System.out.println("No error found");
    }
    The latter approach is used in the standard java.io package, in which you continue to readLine() until the returned String == null.

    I suggest you not to use collections in this case, bacuse it is simply unnecessary. Moreover you should cast and know exactly what the order of the elements in your Collection is.

    Luck

  6. #6
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

  7. #7
    MuslimCoder is offline Senior Member
    Join Date
    Jan 2009
    Posts
    119
    Rep Power
    0

    Default

    I am new to java...

    Would you think of this a good use of the Array?

    <code>
    public class Test
    {

    public static String[] Check(String s)
    {
    // do some checking...
    String a[] = {"true", "Error......"};

    return a;
    }

    public static void main(String args[])
    {
    String[] err;
    String s = "hello";

    err = Check(s);
    System.out.println( "Err: " + err[0] + " Description: " + err[1]);

    }


    }
    </code>

    How do you enclose the Java code??? :)

  8. #8
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default

    Yes, I disagree with you and dswastik. Sorry :(
    If you use a collection in this case
    Quote Originally Posted by myself
    you should cast and know exactly what the order of the elements in your Collection is
    I think you do agree with me that, in this case, there is no real need to return 2 things.

  9. #9
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default

    @MuslimCoder
    How do you enclose the Java code???
    Select the text and then click on the # button (the third from the right)

  10. #10
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    What you exactly want to do with this code?

    Read our FAQ page on the left-side panel of this page. There are lots of things helpful to you.

  11. #11
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by raffaele181188 View Post
    Yes, I disagree with you and dswastik. Sorry :(
    If you use a collection in this case

    I think you do agree with me that, in this case, there is no real need to return 2 things.
    Yes I agreed with you. Actually what I want to pointed in my first post is, collection is the best choice. But have think about few things as you explain. It's not good with those types use in this code, but for the multiple return it's nice. Isn't it?

  12. #12
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default

    Quote Originally Posted by Eranga
    What you exactly want to do with this code?
    @Eranga
    I think MuslimCoder just tried to solve itaipee's problem using arrays

  13. #13
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default

    Quote Originally Posted by Eranga
    It's not good with those types use in this code, but for the multiple return it's nice. Isn't it?
    No it isn't nice...:p It's simply PERFECT :D
    THAT is the way they are supposed to be used. But usually, when using Collections, you put into them the same type of Object. Then you can:
    • Retrieving them without a cast using generics
    • use an enhanced for loop to iterate through the elements

    But to do these things the elements in your Collection ARE TO BE the same type. Often, when you feel you need a Collection filled with different types, you are making a design mistake (like itaipee).

  14. #14
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Quote Originally Posted by raffaele181188 View Post
    No it isn't nice...:p It's simply PERFECT :D
    THAT is the way they are supposed to be used. But usually, when using Collections, you put into them the same type of Object. Then you can:
    • Retrieving them without a cast using generics
    • use an enhanced for loop to iterate through the elements

    But to do these things the elements in your Collection ARE TO BE the same type. Often, when you feel you need a Collection filled with different types, you are making a design mistake (like itaipee).
    100 mark to you. I agreed with you lol.

  15. #15
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Eranga is right in this case, return a collection is the best approach. To keep it simple, use ArrayList. Using arrays ends up being complicated.

    You could just return a String, but that would limit you to one error.

    In your checker, create an empty ArrayList, new ArrayList<String>. If errors are found, add messages. Return the ArrayList.

    In the caller, check if the ArrayList has any entries (size() == 0). If there are no entries, there are no errors.

    Using the ArrayList approach, you can also create an ErrorMessage class with multiple fields, which is useful for more advanced applications.

  16. #16
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    By the way, an occasionally useful technique for "returning" more than one value is for the caller to pass to the method an array to be filled with a return value. In general, it's not terribly "good design", but it can get you round some of the "object handling messiness" in a few limited cases. For example, if you have a method that you want to return, say, a String and an int, then you could declare the method as follows:

    Java Code:
    public String performOperation(int[] retVal) {
       ...
       retval[0] = integer_to_be_returned;
       return string_to_be_retured;
    }
    Now, the caller does something such as follows:

    Java Code:
    int[] intRet = new int[1]
    ...
    for (int i = 0; i < noOps; i++) {
      String str = performOperation(intRet);
      int intVal = intRet[0];
      ...
    }
    Obviously, you have to decide when you're introducing an ugly API design by doing this and when you're using the pattern to "get you out of a hole".

    There are occasional uses in the JDK (I seem to recall there are examples inside the bowels of Swing for dealing with laying out elements of styled text editors, for example).

  17. #17
    Join Date
    Dec 2008
    Location
    Italy
    Posts
    79
    Rep Power
    0

    Default


    • Quote Originally Posted by steve
      You could just return a String, but that would limit you to one error
      Yes, this is the thing itaipee talked about:
      Quote Originally Posted by itaipee
      I want them to return 2 things : boolean for if the check passed. and string for telling what the error is

    • Quote Originally Posted by steve
      In the caller, check if the ArrayList has any entries (size() == 0). If there are no entries, there are no errors.
      This is one right way if he would like to return MULTIPLE errors, but it doesn't seem so in his original post.

    • Quote Originally Posted by Steve
      Using the ArrayList approach, you can also create an ErrorMessage class with multiple fields, which is useful for more advanced applications
      Yes, another way to do the task and MuslimCoder argued it, yet. But IF he needs multiple errors


    @steve
    The fact is, he was told to use Collections to return a Boolean and a String, not multiple errors... So we told him he were the wrong way because it makes little sense to put in the same List a Bool and a String.

    @itaipee
    If your string may contains multiple errors then you are FORCED to return an array or a Collection. Then your original post is misleading

  18. #18
    itaipee is offline Member
    Join Date
    Dec 2008
    Posts
    99
    Rep Power
    0

    Default

    returning an array, list or collection - how should I say it, it does not look nice .
    But I guess it is the simplest solution ( I didn't think on it but multiply error may be needed so returning one String may also not do the trick)

    @Rafael
    the all "try" and "catch" look like best , but I have to learn how to use it

  19. #19
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    7

    Default Return string?

    If you don't like returning the array, return a string with the all the info you need and just parse it.
    something like:

    msg = "false: error msg"
    or
    msg = "true"

    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  20. #20
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default It's not that hard

    Java Code:
    public class Message {
      private int _ID;
      private final String _Text;
      public Message(final int pID, final String pText) {
        _ID = pID;
        _Text = pText;
      }
      public int getID() {
        return _ID;
      }
      public String getText() {
        return _Text;
      }
    }
    .
    .
    .
      public ArrayList<Message> validate() {
        final ArrayList<Message> messages = new ArrayList<Message>();
        if (some error) {
          messages.add(1, "Some error occurred.");
        }
        return messages;
      }
    .
    .
    .
        final ArrayList<Message> messages = validate();
        if (messages.size() > 0) {
          // display the messages
          // skip processing
        }
        // do processing
    Of course, the Message class could contain other information as well, or just text. If the ArrayList has no messages, no error occurred. This approach is simple and powerful, and it doesn't involve any kludge code for parsing.

Similar Threads

  1. Static Method and Return Statements
    By berelson in forum New To Java
    Replies: 2
    Last Post: 11-29-2008, 11:17 PM
  2. return a null method
    By valoyivd in forum New To Java
    Replies: 2
    Last Post: 04-21-2008, 11:19 PM
  3. Using final with method arguments
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-17-2008, 07:48 PM
  4. Return question in a method.
    By MetalGear in forum New To Java
    Replies: 1
    Last Post: 01-13-2008, 04:45 AM
  5. Return value of method
    By cachi in forum New To Java
    Replies: 1
    Last Post: 08-01-2007, 08:23 AM

Posting Permissions

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