Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 01-08-2009, 12:31 PM
Member
 
Join Date: Dec 2008
Posts: 98
Rep Power: 0
itaipee is on a distinguished road
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 ?

Code:
//what I want 
String str=null;
if (checkErrorMethod(str)==true)
      System.out.println("this is the error :"+str);
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 01-08-2009, 12:50 PM
Senior Member
 
Join Date: Dec 2008
Posts: 164
Rep Power: 2
dswastik is on a distinguished road
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));
}
}
}
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 01-08-2009, 12:58 PM
Senior Member
 
Join Date: Jan 2009
Posts: 116
Rep Power: 0
MuslimCoder is on a distinguished road
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.
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 01-08-2009, 12:59 PM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 7,523
Rep Power: 11
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
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.
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
Someone helped you? their helpful post.
Help:Forums FAQ|How To Ask Questions The Smart WayResources:The Java Tutorials|Glossary for Java|NetBeans IDE|Sun DownloadsWeb:WritOnceTips:Is your IDE the best?|Which Application Server?
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 01-08-2009, 01:34 PM
Member
 
Join Date: Dec 2008
Location: Italy
Posts: 79
Rep Power: 0
raffaele181188 is on a distinguished road
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:
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):
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
Bookmark Post in Technorati
Reply With Quote
  #6 (permalink)  
Old 01-08-2009, 01:42 PM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 7,523
Rep Power: 11
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
Default
Are you disagreed with my comment raffaele?
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
Someone helped you? their helpful post.
Help:Forums FAQ|How To Ask Questions The Smart WayResources:The Java Tutorials|Glossary for Java|NetBeans IDE|Sun DownloadsWeb:WritOnceTips:Is your IDE the best?|Which Application Server?
Bookmark Post in Technorati
Reply With Quote
  #7 (permalink)  
Old 01-08-2009, 01:59 PM
Senior Member
 
Join Date: Jan 2009
Posts: 116
Rep Power: 0
MuslimCoder is on a distinguished road
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???
Bookmark Post in Technorati
Reply With Quote
  #8 (permalink)  
Old 01-08-2009, 02:02 PM
Member
 
Join Date: Dec 2008
Location: Italy
Posts: 79
Rep Power: 0
raffaele181188 is on a distinguished road
Default
Yes, I disagree with you and dswastik. Sorry
If you use a collection in this case
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.
Bookmark Post in Technorati
Reply With Quote
  #9 (permalink)  
Old 01-08-2009, 02:04 PM
Member
 
Join Date: Dec 2008
Location: Italy
Posts: 79
Rep Power: 0
raffaele181188 is on a distinguished road
Default
@MuslimCoder
Quote:
How do you enclose the Java code???
Select the text and then click on the # button (the third from the right)
Bookmark Post in Technorati
Reply With Quote
  #10 (permalink)  
Old 01-08-2009, 02:07 PM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 7,523
Rep Power: 11
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
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.
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
Someone helped you? their helpful post.
Help:Forums FAQ|How To Ask Questions The Smart WayResources:The Java Tutorials|Glossary for Java|NetBeans IDE|Sun DownloadsWeb:WritOnceTips:Is your IDE the best?|Which Application Server?
Bookmark Post in Technorati
Reply With Quote
  #11 (permalink)  
Old 01-08-2009, 02:11 PM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 7,523
Rep Power: 11
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
Default
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?
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
Someone helped you? their helpful post.
Help:Forums FAQ|How To Ask Questions The Smart WayResources:The Java Tutorials|Glossary for Java|NetBeans IDE|Sun DownloadsWeb:WritOnceTips:Is your IDE the best?|Which Application Server?
Bookmark Post in Technorati
Reply With Quote
  #12 (permalink)  
Old 01-08-2009, 02:14 PM
Member
 
Join Date: Dec 2008
Location: Italy
Posts: 79
Rep Power: 0
raffaele181188 is on a distinguished road
Default
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
Bookmark Post in Technorati
Reply With Quote
  #13 (permalink)  
Old 01-08-2009, 02:19 PM
Member
 
Join Date: Dec 2008
Location: Italy
Posts: 79
Rep Power: 0
raffaele181188 is on a distinguished road
Default
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... It's simply PERFECT
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).
Bookmark Post in Technorati
Reply With Quote
  #14 (permalink)  
Old 01-08-2009, 02:27 PM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 7,523
Rep Power: 11
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
Default
Originally Posted by raffaele181188 View Post
No it isn't nice... It's simply PERFECT
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.
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
Someone helped you? their helpful post.
Help:Forums FAQ|How To Ask Questions The Smart WayResources:The Java Tutorials|Glossary for Java|NetBeans IDE|Sun DownloadsWeb:WritOnceTips:Is your IDE the best?|Which Application Server?
Bookmark Post in Technorati
Reply With Quote
  #15 (permalink)  
Old 01-08-2009, 04:55 PM
Steve11235's Avatar
Senior Member
 
Join Date: Dec 2008
Posts: 972
Rep Power: 2
Steve11235 is on a distinguished road
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.
Bookmark Post in Technorati
Reply With Quote
  #16 (permalink)  
Old 01-08-2009, 07:56 PM
Senior Member
 
Join Date: Nov 2008
Posts: 275
Rep Power: 2
neilcoffey is on a distinguished road
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:

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:

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).
__________________
Neil Coffey
Javamex - Java tutorials and performance info
Bookmark Post in Technorati
Reply With Quote
  #17 (permalink)  
Old 01-08-2009, 08:02 PM
Member
 
Join Date: Dec 2008
Location: Italy
Posts: 79
Rep Power: 0
raffaele181188 is on a distinguished road
Default

  • 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:
    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

  • 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.

  • 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
Bookmark Post in Technorati
Reply With Quote
  #18 (permalink)  
Old 01-11-2009, 10:45 AM
Member
 
Join Date: Dec 2008
Posts: 98
Rep Power: 0
itaipee is on a distinguished road
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
Bookmark Post in Technorati
Reply With Quote
  #19 (permalink)  
Old 01-12-2009, 05:02 PM
CJSLMAN's Avatar
Moderator
 
Join Date: Oct 2008
Location: Mexico
Posts: 1,159
Rep Power: 3
CJSLMAN is on a distinguished road
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.
Bookmark Post in Technorati
Reply With Quote
  #20 (permalink)  
Old 01-12-2009, 06:36 PM
Steve11235's Avatar
Senior Member
 
Join Date: Dec 2008
Posts: 972
Rep Power: 2
Steve11235 is on a distinguished road
Default It's not that hard
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.
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Static Method and Return Statements berelson New To Java 2 11-30-2008 12:17 AM
return a null method valoyivd New To Java 2 04-22-2008 12:19 AM
Using final with method arguments Java Tip java.lang 0 04-17-2008 08:48 PM
Return question in a method. MetalGear New To Java 1 01-13-2008 05:45 AM
Return value of method cachi New To Java 1 08-01-2007 09:23 AM


All times are GMT +2. The time now is 07:07 AM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org