Return values and methods repost

Had to repost for clarity. I'm working on a program which not only could I not compile...and have already been adviced on the forum it's well of the mark. Kindly request a few pointers ( !code ) on where i'm going wrong. I'll put the question as put to me and the code I originally thought was close to archieving th task.
Here goes,
The following code fragment is the main method for a simple program. The program reads in the ages of 3 people. Each age is checked for validity. If all ages are valid the program will then calculate the age of the oldest person and the average age(which is to be represented as a double).
The method names highlighted in bold require implementation(note some method calls are duplicated, but this doesn't mean you have to write the method more than once!). The first takes an integer parameter and returns true or false depending on whetherthe age is valid, i.e. between some sensible limits. The remaining methods both take threeparameters, all intergers. oldest displays the highest age value; average returns the average of the ages.
public class Tut11_1{
public static void main(String[] args){
    GUI gui=new GUI();
    int age1=0;
    int age2=0;
    int age3=0;
    double average=0;
    age1=gui.getInt("Enter first age");
    age2=gui.getInt("Enter second age");
    age3=gui.getInt("Enter third age");
    if(!isValidAge(age1))
         gui.putText("Age 1 is not valid");
    else if(!isValidAge(age1))
         gui.putText("Age 2 is not valid");
    else if(!isValidAge(age1))
         gui.putText("Age 3 is not valid");
    else
         oldest(age1, age2, age3);
         average=averageAge(age1, age2, age3);
         gui.putText("Average age is " + average);
    This is where i've got to....
public class Tut11_1{
public static void main(String[] args){
    GUI gui=new GUI();
    int age1=0;
    int age2=0;
    int age3=0;
    double average=0;
    age1=gui.getInt("Enter first age");
    age2=gui.getInt("Enter second age");
    age3=gui.getInt("Enter third age");
    if(!isValidAge(age1))
         gui.putText("Age 1 is not valid");
    else if(!isValidAge(age1))
         gui.putText("Age 2 is not valid");
    else if(!isValidAge(age1))
         gui.putText("Age 3 is not valid");
    else
         oldest(age1, age2, age3);
         average=averageAge(age1, age2, age3);
         gui.putText("Average age is " + average);
    //implementing method names
    public static Boolean isValidAge(int oldest, double averageAge, double average)
         if(isValidAge<=0)
              return false;
         else if(isValidAge<=100)
              return true;
         else if(isValidAge>100)
              return false;
         else
              oldest(age1, age2, age3);
            return oldest;
            average=averageAge(age1, age2, age3);
            return average;
    }

N_E_W_B_I_E wrote:
That seem to make sense...will give that a go. On the case of boolean would this be right?
public static boolean isValidAge(_DONT I HAVE TO DECLARE ANYTHING HERE_ )To be honest with you I am not seeing alot of hope of you completing this assignment without one on one help.
This is just to give you a push in the right direction. I wouldn't normally do this but it's not all of your assignment and there seems to be a real lack of progress in your two threads thus far....
public static boolean isValidAge(int age){
  if(age<=0){
    return false;
  return age<100;
}So that method is now finished. When you call it you can do this...
int x = 17;//or whatever the user inputs
boolean validAge = isValidAge(x);
if(validAge==true){
}else{
}The above can be compressed (because an if is a true/false and boolean is a true false) as
int x = 17;//or whatever the user inputs
if(isValidAge(x)){
}else{
}

Similar Messages

  • Client/server RMI app using Command pattern: return values and exceptions

    I'm developing a client/server java app via RMI. Actually I'm using the cajo framework overtop RMI (any cajo devs/users here?). Anyways, there is a lot of functionality the server needs to expose, all of which is split and encapsulated in manager-type classes that the server has access to. I get the feeling though that bad things will happen to me in my sleep if I just expose instances of the managers, and I really don't like the idea of writing 24682763845 methods that the server needs to individually expose, so instead I'm using the Command pattern (writing 24682763845 individual MyCommand classes is only slightly better). I haven't used the command pattern since school, so maybe I'm missing something, but I'm finding it to be messy. Here's the setup: I've got a public abstract Command which holds information about which user is attempting to execute the command, and when, and lots of public MyCommands extending Command, each with a mandatory execute() method which does the actual dirty work of talking to the model-functionality managers. The server has a command invoker executeCommand(Command cmd) which checks the authenticity of the user prior to executing the command.
    What I'm interested in is return values and exceptions. I'm not sure if these things really fit in with a true command pattern in general, but it sure would be nice to have return values and exceptions, even if only for the sake of error detection.
    First, return values. I'd like each Command to return a result, even if it's just boolean true if nothing went wrong, so in my Command class I have a private Object result with a protected setter, public getter. The idea is, in the execute() method, after doing what needs to be done, setResult(someResult) is called. The invoker on the server, after running acommand.execute() eventually returns acommand.getResult(), which of course is casted by the client into whatever it should be. I don't see a way to do this using generics though, because I don't see a way to have the invoker's return value as anything other than Object. Suggestions? All this means is, if the client were sending a GetUserCommand cmd I'd have to cast like User user = (User)server.executeCommand(cmd), or sending an AssignWidgetToGroup cmd I'd have to cast like Boolean result = (Boolean)server.executeCommand(cmd). I guess that's not too bad, but can this be done better?
    Second, exceptions. I can have the Command's execute() method throw Exception, and the server's invoker method can in turn throw that Exception. Problem is, with a try/catch on the client side, using RMI (or is this just a product of cajo?) ensures that any exception thrown by a remote method will come back as a java.lang.reflect.InvocationTargetException. So for example, if in MyCommand.execute() I throw new MySpecialException, the server's command invoker method will in turn throw the same exception, however the try/catch on the client side will catch InvocationTargetException e. If I do e.getCause().printStackTrace(), THERE be my precious MySpecialException. But how do I catch it? Can it be caught? Nested try/catch won't work, because I can't re-throw the cause of the original exception. For now, instead of throwing exceptions the server is simply returning null if things don't go as planned, meaning on the client side I would do something like if ((result = server.executeCommand(cmd)) == null) { /* deal with it */ } else { /* process result, continue normally */ }.
    So using the command pattern, although doing neat things for me like centralizing access to the server via one command-invoking method which avoids exposing a billion others, and making it easy to log who's running what and when, causes me null-checks, casting, and no obvious way of error-catching. I'd be grateful if anyone can share their thoughts/experiences on what I'm trying to do. I'll post some of my code tomorrow to give things more tangible perspective.

    First of all, thanks for taking the time to read, I know it's long.
    Secondly, pardon me, but I don't see how you've understood that I wasn't going to or didn't want to use exceptions, considering half my post is regarding how I can use exceptions in my situation. My love for exception handling transcends time and space, I assure you, that's why I made this thread.
    Also, you've essentially told me "use exceptions", "use exceptions", and "you can't really use exceptions". Having a nested try/catch anytime I want to catch the real exception does indeed sound terribly weak. Just so I'm on the same page though, how can I catch an exception, and throw the cause?
    try {
    catch (Exception e) {
         Throwable t = e.getCause();
         // now what?
    }Actually, nested try/catches everywhere is not happening, which means I'm probably going to ditch cajo unless there's some way to really throw the proper exception. I must say however that cajo has done everything I've needed up until now.
    Anyways, what I'd like to know is...what's really The Right Way (tm) of putting together this kind of client/server app? I've been thinking that perhaps RMI is not the way to go, and I'm wondering if I should be looking into more of a cross-language RPC solution. I definitely do want to neatly decouple the client from server, and the command pattern did seem to do that, but maybe it's not the best solution.
    Thanks again for your response, ejp, and as always any comments and/or suggestions would be greatly appreciated.

  • Handling the return values and passing values to a dialog

    Dear all,
    I am trying to return values from a dialog to a page.
    I am following a tutorial:
    http://www.oracle.com/technology/products/jdev/101/howtos/adfdialog/index.html
    its okey, but I couldnt understand the following code:
    public void handleReturn(ReturnEvent event)
    if (event.getReturnValue() != null)
    Customer cst;
    String name;
    String psw;
    cst = (Customer)event.getReturnValue();
    CustomerList.getCustomers().add(cst);
    name = cst.getFirstName();
    psw = cst.getPassword();
    inputText1.setSubmittedValue(null);
    inputText1.setValue(name);
    inputText2.setSubmittedValue(null);
    inputText2.setValue(psw);
    please help me what are these variables?
    that I could be able to map with me own.
    Regards:
    Muhammad Nadeem
    [email protected]

    If you look further down on the tutorial, you will notice that these values are set in the dialog done() and cancel() actionListeners. Similarly, you will return your own object(s) when calling returnFromProcess() - see the done() method.
    Regards,
    Nick

  • Create SP that returns value and at the same time displays query result in output window

    I would like create an SP which will return the records from the table and also return value to my c# client application.
    For Example:
    Select * from employee returns all the query results in output window.
    Now I want to create an SP
    Create procedure Test
    As
    Declare @ret int,
    Select * from employee
    set @ret = Select count(*) from employee
    if @ret > 0
    return 1
    else
    return 0
    The above algo should return 1 0r 0 to c# client application and at the same time display all employees in sql query output window.
    Can u pls help in this regard.

    The above algo should return 1 0r 0 to c# client application and at the same time display all employees in sql query output window.
    Why?  and No!
    Why?  Your procedure generates a resultset of some number of rows.  You check the resultset for the presence of rows to determine if "anything is there".  You don't need a separate value to tell you this.  Note that it helps
    to post tsql that is syntactically correct.   While we're at it, if you just need to know that rows exist there is no need to count them since that does more work than required.  Simply test for existence using the appropriately-named function
    "exists".  E.g., if exists (select * from dbo.employee). 
    No!  A stored procedure does not display anything anywhere.  The application which executes the procedures is responsible for the consumption of the resultset; it chooses what to do and what to display. 
    Lastly, do not get into the lazy habit of using the asterisk in your tsql code.  That is not best practice.  Along with that, you should also get into the following best practice habits:
    schema-qualify your objects (i.e., dbo.employee)
    terminate every statement - it will eventually be required.

  • List Managers Displays Return Value and Not Display Value

    Hi
    I have created a List Manager (based on a Popup LOV). My lov is as follows:
    SELECT pt.paper_code d, pt.paper_icode r
    FROM uo_sturec.paper_table pt
    WHERE pt.start_year <= 2006
    AND (pt.finish_year >= 2006 OR pt.finish_year = 0)
    AND pt.paper_type = 60
    ORDER BY pt.paper_code
    However, when I select something from the popup, it displays the pt.paper_icode in the field and when I click on Add, the pt.paper_icode is added to the selction box.
    What can I do to make the display value, pt.paper_code appear both in the field and the selection box?
    Kind regards
    Jo

    Hi Scott
    Thank you for your reply. However, I want the return value to be pt.paper_icode, because I'll be using this value to populate another item on the same page. Is there some javascript I could write to just change the display value of the List Manager while preserving its return value?
    Thanks.
    Jo

  • Multi-select lists, their return values and showing their display value

    I have a multi select list which is dynamic. The display and return values are pulled from a table where the return value is the Primary Key.
    When people select a few options, the value is stored in session state as 11:12:13 (etc...). From here, I run these numbers through a process which takes a report ID and the multi-select string, and saves individual rows as Report_id, individual multi select value until there are no more multi select values.
    This is great, they're tied in as a foreign key to the LOV lookup table, and they are easily search able.
    I have trouble where I want to list a report's entire multi-select list. I have a function combine the numbers with a : in between them and RTRIM the last one, so I have an identical string to what a multi-select table uses. 11:12:13 (etc..)
    When I assign it to display as an LOV in a report, it just shows the 11:12:13 instead of listing out the values.
    Single number entries, where someone only selected one option in a multi select, display fine.
    Am I doing this wrong?

    Scott - you're right on the money. I did this initially because I thought assigning an LOV display value to a report column would yield the results I wanted.
    I want to do this without referring to the original table... meaning I don't want a function to have to go out and get the names, I'd like my LOV assignment to do it. This saves headache of having to change something in 2 places if it ever changed.
    Am I not going to be able to do this?
    I created a test multi-LOV page, it doesn't work with original(not processed in my function) LOV assignments either, unless you only select one.

  • Returning Values from Methods

    We ran across some code in one of our classes that calls a private method. That method returns an object, but the code calling that method does not capture it. What happens to the return value in a case like this? I would have thought that to be a syntax error.
    Example:
    myMethod(myObject, i);  // Call to myMethod without capturing its return value.
    private myObject myMethod(MyObject myObject, int i) {
       return myObject;
    }What happens to the return value from myMethod?

    (void) f(arg1, ..., argN); There's no
    provision in Java to allow you express that same
    intention.
    What?!?!?public void f(arg1, ...,
    argN);
    In the C code, function f was defined as having a non-void return type.
    The statement
    (void) f(arg1, ..., argN);shows the caller is knowing ignoring that returned value.

  • Return values of methods

    If a method has a return type, either a primitive or an Object type or any other user-defined type, what happens to the return value if it is not used.
    For eg., if I have a hashtable MyHash, I would use the put() method to fill it up. The put() has a return type of Object. However, I don't need the return type so I ignore it. Does the returned Object occupy any memory space...or is it garbage collected if it is not referenced....what happens to this lost value??

    If you do not keep a reference it should be garbage collected. At what time is up to the garbage collector.

  • Bug? EJB method Return Value and Client Catch the Exception?

    oc4j 9.0.3 on the windows 2000
    I write a Stateless Session Bean named SB1 ,
    and define application exception.
    The Code as follow:
    public class AppErrorException extends Exception
    public interface SB1 extends EJBObject
    public String getMemono(String sysID, String rptKind, String parentMemono)
    throws RemoteException, AppErrorException;
    public class SB1Bean implements SessionBean
    public String getMemono(String sysID, String rptKind, String parentMemono)
    throws RemoteException, AppErrorException
    throw new AppErrorException("Error in getMemono");
    public class SB1TestClient
    try
    memomo= sb1.getMemono(.....);
    catch(AppErrorException ae)
    ae.printStackTrace();
    I found a bug.
    If SB1.getMemono() throws the AppErrorException, but SB1TestClient will not catch any Exception.
    It is not normal!!!!
    [cf]
    But If I convert "public String getMemono(...)" into "public void getMemono(...)",
    When SB1.getMemono() throws the AppErrorException, but SB1TestClient will catch any Exception.
    It is normal.

    getMemono(.......)'s code as follow:
    public String getMemono(String sysID, String rptKind, String parentMemono)
    throws AppErrorException
    log("getMemono("+sysID+", "+rptKind+", "+parentMemono+")");
    Connection connection= null;
    CallableStatement statement = null;
    String memono= "";
    short retCode= -1;
    String retMsg= "";
    try
    String sql= this.CALL_SPGETMEMONO;
    connection = ResourceAssistant.getDBConnectionLocal("awmsDS");
    statement= connection.prepareCall(sql);
    statement.setString(1, sysID.trim());
    statement.setString(2, rptKind.trim());
    statement.setString(3, parentMemono.trim());
    statement.registerOutParameter(4, java.sql.Types.VARCHAR);
    statement.registerOutParameter(5, java.sql.Types.SMALLINT);
    statement.registerOutParameter(6, java.sql.Types.VARCHAR);
    statement.executeQuery();
    retCode= statement.getShort(5);
    retMsg= statement.getString(6);
    log("retCode="+retCode);
    log("retMsg="+retMsg);
    if (retCode==AppConfig.SHORT_SP_RETCODE_FAILED)
    log("retCode==AppConfig.SHORT_SP_RETCODE_FAILED");
    this.sessionContext.setRollbackOnly();
    throw new AppErrorException(retMsg);
    memono= statement.getString(4);
    log("memono="+memono);
    if (rptKind.trim().length()<6)
    log("rptKind.trim().length()<6");
    this.sessionContext.setRollbackOnly();
    throw new AppErrorException("rptKind.trim().length()<6");
    memono= "SS";
    catch (AppErrorException ae)
    log("catch(AppErrorException ae)");
    throw ae;
    //throw new EJBException(ae.getErrMsg());
    catch (Exception e)
    log("catch (Exception e)");
    this.sessionContext.setRollbackOnly();
    throw new AppErrorException(IExceptionConst.ERR_MSG_SYSMEMONO_00000, e.toString());
    //throw new EJBException(IExceptionConst.ERR_MSG_SYSMEMONO_00000+", "+e.toString());
    finally
    log("this.sessionContext.getRollbackOnly()="+this.sessionContext.getRollbackOnly());
    ResourceAssistant.cleanup(connection,statement);
    return memono;

  • Date return values and nullpointerexception

    Couple of problems I was hoping to find some help about:
    First, I'm passing a String, Number and Date into a private static void method. The String and Number values are updated and returned / retrieved fine, but the Date isn't and holds it's original value. How do I get a Date value, updated within the method, to be returned?
    Second, I get a NullPointerException from the following little slice of code. The Olistitem is a class created by JPub FYO.
    Olistitem[] listItem = new OSyncEnumlistitem[2];
    listItem[0].setNumbervalue( new BigDecimal(1) ); // It's expecting a BigDecimal.
    Any ideas?
    Thankyou for any help.

    For the first one, probably need some source code to
    answer.
    Are you returning a new Date, or just the original
    object?I'm trying to assign a new date value to the date object passed in and then retrieve the results into an array. Some source code:
    //To call the method.
    Object argsV[] = new Object[argsValue.size()];
    argsValue.toArray(argsV);
    method.invoke(null, argsV);
    // The method itself.
    public static void test(CramerVarchar first, CramerNumber second, java.util.Date third, SyncEnumList fourth) throws ParseException
    try{
    first.setValue("Test String Returned");
    second.setValue(new BigDecimal(second.getValue().intValue() + new BigDecimal(1).intValue()));
    String dateFormat = "dd-MM-yy HH:mm:ss";
    String theDateString = new String ("15-07-03 10:24:05");
    SimpleDateFormat date = new SimpleDateFormat(dateFormat);
    third = date.parse(theDateString);
    catch (SQLException e)
    System.out.println("Error in tester");
    Any clearer as to what I'm getting at?!

  • Standard Report VA05 Adds up Returns Value and Qty :(

    Hi Gurus,
    We have an issue the standard Report VA05 Adds up Qty and Value of Returns Orders/ Credit or Debit Request which gives up a wrong value when you look at the Total.
    I checked up with IDES and it is just the same. Any Help how to overcome the issue
    Regards
    SK

    Hi
    VA05 being a standard order display report it will give you all the order types.
    There are 2 ways of doing this.
    1. Click on addtional selection criteria button and select the sales document type in your selection. You will only get the order types you want.
    2. Run the full report and then filter out the order types you dont want and save that as a variant.  You can set this as defualt variant so when your run next time the unwanted order types like Debit memos, etc will not come in the report.
    Regards
    Yatin Thakkar

  • Exporting and returning value question

    What is different between exporting and returning value in method of a class. if created an object inside the method and exporting it, it means I have a reference to that object inside program. If I use returning value, it means I have a copy of object created inside the method, but the object inside method is destroyed after it ends. Do I understand correctly? if so what do u prefer exporting or returning value? thanks!

    Hello Anthony
    The major difference is that you can have multiple EXPORTING parameters yet only a single RETURNING parameter. In addition, if you have a RETURNING parameter you cannot have EXPORTING parameters simultaneously.
    Defining methods with a single RETURNING parameter is more Java-like than having multiple EXPORTING parameters.
    Whenever possible and sensible I prefer RETURNING parameters over EXPORTING parameters because they allow to use the function method call, e.g.:
    go_msglist = cf_reca_messagelist_create( ).
    Regards
      Uwe

  • Get method return value

    Hi. We're using bytecode instrumentation in a native jvmti agent to monitor method entry/exit. I'd like to capture method return values and report them upon method exit. I see how to obtain local variables, and am indeed doing this when a method is entered; however, I'm not sure how to get a method's return value.
    Thanks for any advice.
    -- david

    You will need to do two things to make this work:
    1) Change the method that your return instrumentation calls to accept a parameter (the return value).
    2) Modify your bytecode instrumentation to call your new function with the return value.

  • Custom method return value will not pass to form

    I have created a custom method in my application module that returns a integer value. I am trying to use this value to fetch a row to populate a form. I cannot seem to get the value returned to populate the methodAction binding for the form.
    I have no problem displaying the returned value and have no problem populating the form if I hard code a value into the methodAction binding.
    I am trying to determine if this is a timing issue on page load, or some other issue with the returned integer.

    Hi,
    sounds like a lifecycle problem because the method call and execution of the VO iterator happen in the same phase. You can try setting the refresh conditions of the method to prepareModel and the iterator to prepareRender, but I doubt that this will solve the issue.
    What is the usecase ? And can the integer be handled within the AM to restrict the query (e.g. to set a ViewCriteria or bind variable)
    Frank

  • How to get both, the ResultSet and Output (return value) from Oracle Stored Procedure

    Hi! I am doing a conversion from MSSQL to Oracle with C++ and MFC ODBC. Any comment is appreciated!! I have Oracle 8i and Oracle ODBC 8.1.6 installed.
    My question is how to retrieve the return value AND ALSO the resultSet at the same time by using Oracle function without modifying my souce codes (except puttting mypackage. string infron of my procedure name, see below).
    -- My source code in C++ with MSSQL ....
    sqlStr.Format("{? = call ListOfCustomers(%i)}", nNameID);
    RcOpen = CustomerList.Open(CRecordset::forwardOnly, sqlStr, CRecordset::readOnly );
    Where CustoemrList is a Crecordset object...
    IN DoFieldExchange(CFieldExchange* pFX) I have ...
    //{{AFX_FIELD_MAP(CQOSDB_Group)
    pFX->SetFieldType(CFieldExchange::outputColumn);
    RFX_Long(pFX, T("Name"), mCustoemrName);
    //}}AFX_FIELD_MAP
    // output parameter
    pFX->SetFieldType( CFieldExchange::outputParam );
    RFX_Int( pFX, T("IndexCount"), mCustomerNumber);
    -- m_CustomerNumber is where i store the return value!!!
    -- In Oracle Version, i have similar codes with ...
    sqlStr.Format("{? = call mypackage.ListOfCustomers(%i)}", nNameID);
    RcOpen = CustomerList.Open(CRecordset::forwardOnly, sqlStr, CRecordset::readOnly );
    -- I have oracle package/Body codes as following...
    create or replace package mypackage
    as
    type group_rct is ref cursor;
    Function listgroups(
    nameID NUMBER ,
    RC1 IN OUT Mypackage.group_rct ) return int;
    end;
    Create or replace package body mypackage
    as
    Function listgroups(
    NameID NUMBER ,
    RC1 IN OUT Mypackage.group_rct )return int
    IS
    BEGIN
    OPEN RC1 FOR SELECT Name
    from Customer
    WHERE ID = NameIDEND ListGroups;
    END
    return 7;
    END listgroups;
    END MyPackage;
    Ive simplified my codes a bit....
    null

    yes, it is exactly what i want to do and I am using Oracle ODBC driver.
    I tried using procedure with 1 OUT var fo numeric value and the other IN OUT ref cursor var instead of function, but error occurs when I called it from the application. It give me a memory ecxception error!!
    sqlStr.Format("{? = call ListOfCustomers(%i)}", nNameID);
    RcOpen = CustomerList.Open(CRecordset::forwardOnly, sqlStr, CRecordset::readOnly );
    it seems to me that the ? marker var is making all the trouble... can you please give me any more comment on this?? thanks!
    null

Maybe you are looking for

  • Submitted tasks not appearing in the batch monitor

    In other words Compressor seems to be totally useless after the update. I select my preset, and the destination, I click submit, I get the little popup with the name, cluster and priority options, I click submit, and then nothing happens. Nothing at

  • Redirect some users on signon (Tools 8.50)

    All, I have a requirement for a subset of my users (those possessing a certain role) to be redirected to a particular page at logon (i.e. they need to be forwarded to a page without seeing the PIA homepage). These users need to use the same PeopleSof

  • EJB Doubt

    Hi, while running Ejb Client program following message am getting: Exception in thread "main" java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is: *     java.net.SocketException: Connection reset by peer: socket write e

  • Hired a movie, completed download, got stuck processing, can't reclaim space

    Here are the steps that led to my issue: 1. Hired a movie from my iphone 5 2. began download 3. Checked download an hour later and status was 'Processing.....'. Checked Movies and no Hired icon present in bottom nav 4. 6 hours later, still in Process

  • I can't install latest Firefox 3.6.13 due to "lack of sufficient privileges". What does this mean. Is there anything I can do.

    I have a iBookG4. I currently have Firefox 3.6.2 I understand Firefox 3.6.13 is the most recent update. When I am asked do you want to replace the old version with the new, I get the message "operation can't be completed because you don't have suffic