Return statement : Not exactly it

I have a method that returns an Element and thru the method I have 3 for loops where I create and populate the elemet, now that the return statement is not withing the for loops I only get one Element., even though the program has 2 or more elements that it's printed.
Here's part of the method just to demo what I mean
public Element show() throws Exception {
Element activitySummary = null;
  try {
    String act[] = new String [6];
    String so[] = new String [9];
    String rac[] = new String [4];
      for(int b = 0; b < act.length; b++){
        if (act[b] != null) {
          activitySummary = new Element("ActivitySummary");
          Element activityType = new Element("ActivityType");
          activityType.setText(act);
activitySummary.getContent().add(0, activityType);
for(int c= 0; c < so.length; c++){
if(so[c] != null){
Element socLine = new Element("SOCLine");
Element soc = new Element("SOC");
soc.setText(so[c]);
socLine.addContent(soc);
activitySummary.addContent(socLine);
for (int d = 0; d < rac.length; d++) {
if (rac[d] != null) {
Element raceRow = new Element("RaceRow");
Element race = new Element("Race");
Element maleT = new Element("MaleTotal");
maleT.setText(" " +MaleTotal[b][c][d]);
Element femaleT = new Element("FemaleTotal");
femaleT.setText(" "+ FemaleTotal[b][c][d]);
Element disabledT = new Element("DisabledTotal");
disabledT.setText(" "+DisabledTotal[b][c][d]);
race.setText(rac[d]);
raceRow.addContent(race).addContent(maleT);
raceRow.addContent(femaleT).addContent(disabledT);
socLine.addContent(raceRow);
XMLOutputter outputter = new XMLOutputter();
outputter.output(activitySummary, System.out);// printing the activitySummary where I get 3 activitySummary Element
}catch (NullPointerException ex) {
System.out.println(ex);
}catch (Exception e) {
throw e;
}finally {
return activitySummary; // it only returns the last activitySummary Element
Please advice on how can I position my return statement so it works.

Nomatter where you put your return statement it always will return only 1 thing.
If you want your return method to return multiple elements you will have to return an array of Elements or some other Object that contains all the elements

Similar Messages

  • Help with return statements

    Can someone explain to me what a return statement does exactly and how I would use it to return a value in the follwoing type of program.
    Its a array making program that allows up to 25 values with the value 0 stopping the method. I need to be able to display the how many usable values the user input (anywhere from 1-25).
    To do this I need to use a return statement, correct? if so, how do utilize it correctly if it is nesasary I will post the code itself.

    Heres what I have for the code...
    To simplify amounbt of typing(I wrote program in telnet) The beginning is a set of options using switch statement. 4 choices, 1)new data. 2) list the data 3) change the data and 4) exit.
    For the new data I need to have the user input up to 25 values or stop at any time by entering 0. the values also cannot be greater than 12000 or less than -12000. it should also return the number of usable values in the array. The return statement is what I am having trouble with.
    Code...
    static int NewData(double a[]) //This part is not changeable
    {   int 1;
    for(i=0; i<25; i++)
    {  System.out.print("Enter Element"+(i +1)+ "- ");
    a=MyInput.readDouble();
    if (a[i]>12000 || a[i]<-12000)
    {System.out.println("the last value is not valid");
                                 break;}
    if (a[i]==0)
    break;
    } return i;
    As of right now the method functions as is but two things need to be changed or added. If possible the program should now break if the user inputs an element greater than 12000 or less than -12000, it should just reset to the integer they were on. Also, how do I get the return value to display something? have i used it correctly to show the number of usable values ithe user entered?

  • Case Statement Not returning resutlset Varbinary

    Declare @val varbinary
    set @val = cast('123456789' as varbinary) 
    select @val as value -- Varbinary Value Result
    Declare @check bit
    set @check= 1
    --THis Case Statement Not returning Result set in Varbinary  . 
    select case @check when 1 then @val else 1 end as value

    See the below part from MSDN documentation reg return type
    Returns the highest precedence
    type from the set of types in result_expressions and
    the optional else_result_expression. 
    http://msdn.microsoft.com/en-IN/library/ms181765.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • What exactly continue & return statement does

    Hi All,
    Here i what to know what exactly continue & return statement does?Pls. do explain with an example for each.
    Thanx,
    M.Ananthu

    In this example, break would do the same thing that return does.
    import java.awt.*;
    import javax.swing.*;
    public class demo {
      static String[] strings = {
        "", "Mary", "had", "", "a", "test", "little", "lamb"
      public static void main(String[] args) {
        for(int j = 0; j < strings.length; j++) {
          if(strings[j].equals(""))
            continue;
          System.out.println(strings[j] + " ");
          if(strings[j].equals("test"))
            return;
    }

  • Return statement in exception and consequences

    Hi,
    Can any one give me the explanation for my doubt?
    Case 1:
    I am having some code throwing some exception lets say arithematic exception in my try block.
    I caught it in the catch block and at last I am having one finally?
    as per normal order try block next catch block and at last finally will execute.
    I execute the above code by putting a return statement inside catch block.I got the same order of execution irrespective of return statement inside catch?
    What is the significance of return inside catch?
    Case 2:
    Lets take the scenario.
    class MyException
         public static void main(String[] args)
              int i=1,j=0;
              try
                   try
                   System.out.println("the value is: "+(i/j));
                   System.out.println("Inside try block");
                   catch(ArithmeticException e)
                   System.out.println("hi in ame");
                   //return;
              finally
              System.out.println("inner finally");
                                            System.out.println("outer try");
              catch(Exception e)
                             e.printStackTrace();
                   System.out.println("in exception");
              finally
                   System.out.println("plz wait");
    If return statement is there inside the inner try and catch the code out of inside outer try not getting executed Why So?
    Any clarifications?
    Thanking you,
    Murthy.

    First, please format your code as per http://forum.java.sun.com/features.jsp#Formatting
    I'm not sure what part you don't understand.
    .    public static void main(String[] args) {
    .        try {
    .            try {
    .                throw new ArithmeticException();
    .                System.out.println("Inside try block"); // #1
    .            catch(ArithmeticException e) {
    .                System.out.println("hi in ame"); // #2
    .                return;
    .            finally {
    .                System.out.println("inner finally"); // #3
    .            System.out.println("outer try"); // #4
    .        catch(Exception e) {
    .            System.out.println("in exception"); // #5
    .        finally {
    .            System.out.println("plz wait"); // #6
    .    }#1 -- You won't get here because you throw AME.
    #2 -- You will get here because you caught the AME you just threw.
    #3 -- You will get here because it's a finally
    #4 -- You won't get here. I think that this is what you're asking about: Why don't we get here? Because we've already done 'return' and this line is NOT inside a finally. The only things that can get executed after a return are finally blocks.
    #5 -- You won't get here because you already caught the AME and didn't rethrow it or any other exception.
    #6 -- You will get here because it's a finally.
    Once you do a return, the only code you can execute before exiting the method are finally blocks. First the one corresponding to the try/cathc block where your return is, then the finally for the try/catch that encloses that one, and so on outward. The code between one finally and the next (#4 here) is NOT executed.
    If you still have a question, please try to clarify exactly what behavior you don't understand.
    Don't return from inside t/c/f.

  • Problems with asynchronous(?) function call before return statement

    I have a function as following inside a class deriving from CustomNode:
    override protected function create () : Node {
                    parseContent();
                    return group;
            }parseContent() executes a HttpRequest and then a PullParser. At least that's what it should do. But actually, it doesn't. Is this because the HttpRequest is asynchronous and is "cancelled" because of the return statement? Or can't this be the problem?

    You would have to update or create the view in the finally block of the onOutput: or onInput methods within the request.
    You could also try
    var viewContent: Node;
    override protected function create () : Node {
                    parseContent();
                    FX.deferAction(function():Void{
                           viewContent = group;
                    return Group{ content: bind viewContent }
            }I never tried that, but it might work.
    Another option is to bind the parsed content to whatever view you are pushing it to. Then whenever the request is done, the view will populate its content on the change of the variable where the content is stored.
    Example:
    var allTables: TableModel[];      
    //***************start of table list decleration****************************\\
    public var list: SwingJList = SwingJList {
        var shortcutKey: Boolean = false;
        focusTraversable: true
        selectedIndex: 0
        action: function(){
            FX.deferAction(function():Void{
                openButton.fire();
        items: bind for( table in allTables ){
            table.name
    var searchDataXml = xmlGenerator.generateSearchXMLString(searchData);
    var contentLength: Integer = searchDataXml.getBytes().length;
    def postRequest: HttpRequest = HttpRequest {
        location: "{WEB_APPLICATION_REQUEST_URL}searchData/?database={DATABASE_KEY}";
        method: HttpRequest.POST;
        headers: [
                HttpHeader {
                    name: HttpHeader.CONTENT_TYPE;
                    value: "application/xml";
                HttpHeader {
                    name: HttpHeader.CONTENT_LENGTH;
                    value: "{contentLength}";
        onStarted: function() {
            println("onStarted - started performing method: {postRequest.method} on location: {postRequest.location}");
        onConnecting: function() { println("onConnecting") }
        onDoneConnect: function() { println("onDoneConnect") }
        onWriting: function() { println("onWriting") }
        onOutput: function(os: java.io.OutputStream) {
            try {
                os.write(searchDataXml.getBytes());
            } finally {
                println("onOutput - about to close output stream.");
                os.close();
                os.flush();
        onToWrite: function(bytes: Long) { println("onToWrite - entire content to be written: {bytes} bytes") }
        onWritten: function(bytes: Long) { println("onWritten - {bytes} bytes has now been written") }
        onDoneWrite: function() { println("doneWrite") }
        onReadingHeaders: function() { println("onReadingHeaders") }
        onResponseCode: function(code:Integer) { println("onResponseCode - responseCode: {code}") }
        onResponseMessage: function(msg:String) { println("onResponseMessage - responseMessage: {msg}") }
        onResponseHeaders: function(headerNames: String[]) {
            println("onResponseHeaders - there are {headerNames.size()} response headers:");
            for (name in headerNames) {
                println("    {name}: {postRequest.getResponseHeaderValue(name)}");
        onReading: function() { println("onReading") }
        onToRead: function(bytes: Long) {
            if (bytes < 0) {
                println("onToRead - Content length not specified by server; bytes: {bytes}");
            } else {
                println("onToRead - total number of content bytes to read: {bytes}");
        onRead: function(bytes: Long) {
            // The toread variable is non negative only if the server provides the content length
            def progress =
            if (postRequest.toread > 0) "({(bytes * 100 / postRequest.toread)}%)" else "";
            println("onRead - bytes read: {bytes} {progress}");
        var parser = new XmlPullParser();
        onInput: function(is: java.io.InputStream) {
            // use input stream to access content here.
            // can use input.available() to see how many bytes are available.
            try {
                allTables = parser.processResults(is);
            } finally {
                is.close();
        onException: function(ex: java.lang.Exception) {
            println("onException - exception: {ex.getClass()} {ex.getMessage()}");
        onDoneRead: function() { println("onDoneRead") }
        onDone: function() { println("onDone") }
    postRequest.start();
    } In this case an array of tableModel names are bound to the list view.
    When the httprequest ends, it sets the parsed tableModel array to the array declared in this class.
    The list view will populate the table names from the array when the request finishes.

  • Using return statement in jsp

    Hi all,
    I am using return statement in JSP page after a redirect to stop executing that page. If the data bean is not present then it must go to previous page. When this return statement is executed the previous page is displayed but url in browser remains same. Why it is so ?. Is there any other way to tell a JSP page to stop executing and redirect to another page.
    rgds
    Antony Paul

    Hi Antony,
    do you use the "forward()" method or the "redirect()" method???
    rgds
    Howy

  • Task Flow Return Listener not fire when FK association fields set manually

    Guys and Gals,
    I've spent two solid days on this and I'm not sure why my task flow return listener is not firing.
    I start by selecting a row in a table. I then click a "Convert" button which converts the Quote document into a Sales document. I then press Submit which commits the data and the task flow exits. At this point my task flow return listener should fire. It does not. This return listener would, in theory, refresh the visible Quotes table and update the selected Quote's status to "Closed".
    The Quote's "Closed" status is a transient attribute which is calculated by looking at the Sales' document Qty attribute. If the Quote Qty = Sales Qty, then the status is closed. This can be measured by utilizing an association where
    Sales' BaseRefDocId = Quotes' OrderId
    Sales' BaseRefRowId = Quotes' RowId
    Setting these two row attributes represent the association linking a Quote document row to a Sales document row.
            nvp.setAttribute("BaseRefDocId", baseRow.getAttribute("OrderId"));     // Take the Quote Id and put in the Sales' Id ref field
            nvp.setAttribute("BaseRefRowId", baseRow.getAttribute("Row_Id"));    // Take the Quote Row Id and put it in the Sales Row Id ref field
            targetRow.createAndInitRow(nvp);                                                    // Insert the new referenced row into the Sales' DocumentAfter two days of running tests, it is the code above that keeps the return listener from firing and the transient attribute from refreshing on the page. These fields are not mandatory, but are necessary for the Quotes status to change to closed. Simply leaving these lines of code out allows my task flow return listener to refresh correctly, albeit with an incorrect Quote status.
    My expression language statements, however, evaluate correctly irregardless of table refresh. If I refresh the table manually, the status will then display the correct value. All other methods of manipulating the table function correctly i.e. task flow return statements work.
    I'm pretty sure it has something to do with some kind of silent association / view link error blocking the task flow from firing behind the scenes.
    Does anyone have any ideas? Using JDev 11.1.2.1.0.
    Will

    Hi Frank,
    Yeah, I thought it was really weird as well. I banged my head up against the wall again today and finally managed to semi-fix the problem.
    The "Convert" table toolbar button has a "Disabled" attribute that I've been setting with something like #{bindings.QuoteIterator.currentRow == null}. If I take this out, everything works fine. However, if I put it in, the task flow will not return. What's screwy is that I have several of these "Quote" tables for other data collections such as Sales, Deliveries, Invoices, etc. About half of them fire a task flow return with the "Disabled" attribute set for the convert button, and the other half don't. They all return a task flow return if I just set "Disabled" to false.
    At three days and counting, this is really an issue I just don't get, and I'm not sure if I could reproduce the problem to submit it to support because everything appears just fine and I've been digging for days.

  • Statement not in an executed state. ?

    Hi All,
    I am getting the following error:
    Exception: verifyPassword=java.sql.SQLException: [Microsoft][SQLServer 2000 Driv
    er for JDBC]Invalid operation.  Statement not in an executed state.What could be the problem ?
    Thanks
    Harish Pathak

    Sorry I forgot to place the code..
    here is the code..
    public boolean verifyPassword(String username, String password) {
            String originalPassword=null;
            try {
                Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
               Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://sqlserver:1433","harish","harish");
               PreparedStatement pstmt = con.prepareStatement("select password from registration where username='"+username+"'");          
               ResultSet rs = pstmt.getResultSet();
               if(rs.next()) {
                   originalPassword=rs.getString(1);
               pstmt.close();
               if(originalPassword.equals(password)) {
                   return true;
               } else {
                   return false;
           } catch (Exception e){
               System.out.println("Exception: verifyPassword="+e);
               return false;
        }Please reply soon.

  • Missing return statement - Java noob here

    Hi to everyone! I'll just like to ask if anyone of you can check out my code and see why I can do to correct this 'Missing return statement' problem with my code.
    From what I've been noticing, the compiler returns this statement when the return statements are inside conditional clauses. Usually I've been able to remedy it by storing it into another variable that's been instantiated outside my usual 'if' statements. But this time, it was my first time to use a 'try' statement since FileReader and FileWriter won't work without it. I tried to use the same remedy but it just doesn't work. Here's the part of the code I'm having problems with:
    public String[] sortWordList()
             try
                  FileReader fReader = new FileReader("initlist.txt");
                  BufferedReader bReader = new BufferedReader(fReader);
                  String output = bReader.readLine();
                  String[] words = output.split(",");
                  for(int counter1 = 0; counter1 < words.length; counter1++)
                        for(int counter2 = counter1 + 1; counter2 < words.length; counter2++)
                                  if(words[counter2].compareToIgnoreCase(words[counter1]) < 0)
                                       String temp = words[counter1];
                                       words[counter1] = words[counter2];
                                       words[counter2] = temp;
                   String temp = "";
                   for(int counter1 = 0; counter1 < words.length; counter1++)
                        FileWriter fWriter = new FileWriter("initlist.txt");
                       fWriter.write(words[counter1] + "," + temp);     
                       fWriter.close();
                       temp = bReader.readLine();
                   String output2 = bReader.readLine();
                  String[] words2 = output.split(",");
                  return words2;
             catch(IOException ioe)
        }The compiler points the 'Missing return statement' at the last bracket.
    BTW, just for those who are wonder what we're making, our teacher gave us a machine project where we have to make a basic dictionary (words only, we'll be doing the definitions and other stuff that's associated with the word some other time I think) with input and sort functions.
    Thanks guys!
    - Alphonse

    T.B.M wrote:
    By doing this, we're subverting the exception mechanism and totally defeating the purpose of exceptions. If you're going to catch an exception, you should handle it. Just smothering it and returning null is not handling it. If you're not going to handle it, then don't catch it, or else catch it and wrap it in a more layer-appropriate exception and re-throw.Then ideally there should be some *"return String[];"* statement inside "catch", not after it.No. Not unless there's some meaningful default value to use when the file can't be read, which does not appear to be the case here.
    If you return null, or an empty String[], then the caller will have to do an if test to know that something went wrong and that the method failed to do what it was supposed to do, and then what is the caller supposed to do in that case? The point of exceptions is to avoid those explicit tests for errors and let the "happy path" code just go on under the assumption that things are fine. If something goes wrong, an exception will be thrown and the happy path code will stop excuting, without having to explicitly test for an error condition.

  • Missing Return Statement, where do I put it?

    Hi am using some code from the Sun website, it is called the KnockKnockProtocol, and I have edited it a bit and I get a "missing return statement" error. When I put one in the server does not run at all?
    import java.net.*;
    import java.io.*;
    public class KnockKnockProtocol {
        private static final int WAITING = 0;
        private static final int SENTKNOCKKNOCK = 1;
        private static final int SENTFILE = 2;
        private static final int ANOTHER = 3;
        private static final int NUMJOKES = 5;
        private int state = WAITING;
        private int resource = 0;
        private String[] file = {"1. iTune 2. ZoneAlarm 3. WinRar 4. Audacity (Select a resource for downloading)"};
        private String[] download1 = {"You are downloading iTune.zip."};
        private String[] download2 = {"You are downloading ZoneAlarm.zip."};
        private String[] download3 = {"You are downloading WinRar.zip."};
        private String[] download4 = {"You are downloading Audacity.zip."};
        public String processInput(String theInput) {
            String theOutput = null;
            if (state == WAITING) {
                theOutput = "Here are the terms of reference. Do you accept?";
                state = SENTKNOCKKNOCK;
            } else if (state == SENTKNOCKKNOCK) {
                if (theInput.equalsIgnoreCase("Yes")) {
                    theOutput = file[resource];
                    state = SENTFILE;
                } else {
                    theOutput = "Please accept the terms of reference to continue. Do you accept?";
            } else if (state == SENTFILE) {
                if (theInput.equalsIgnoreCase("1")) {
                    theOutput = download1[resource] + " Do you want to download another?";
                    state = ANOTHER;
                } else if (state == SENTFILE) {
                    if (theInput.equalsIgnoreCase("2")) {
                        theOutput = download2[resource] + " Do you want to download another?";
                        state = ANOTHER;
                    } else if (state == SENTFILE) {
                        if (theInput.equalsIgnoreCase("3")) {
                            theOutput = download3[resource] + " Do you want to download another?";
                            state = ANOTHER;
                        } else if (state == SENTFILE) {
                            if (theInput.equalsIgnoreCase("4")) {
                                theOutput = download4[resource] + " Do you want to download another?";
                                state = ANOTHER;
                        } else {
                            theOutput = "You're supposed to select \"" +
                                    file[resource] +
                                    "\"" +
                                    " Please try again!";
                            state = SENTKNOCKKNOCK;
                    } else if (state == ANOTHER) {
                        if (theInput.equalsIgnoreCase("Yes")) {
                            theOutput = file[resource];
                        if (resource == (NUMJOKES - 1)) {
                            resource = 0;
                        } else {
                            resource++;
                        state = SENTKNOCKKNOCK;
                    } else {
                        theOutput = "Bye.";
                        state = WAITING;
                return theOutput;
    }Any ideas how to solve would be nice. Thanks.

    private String[] file = {"1. iTune 2. ZoneAlarm 3. WinRar 4. Audacity (Select a resource for downloading)"};
        private String[] download1 = {"You are downloading iTune.zip."};
        private String[] download2 = {"You are downloading ZoneAlarm.zip."};
        private String[] download3 = {"You are downloading WinRar.zip."};
        private String[] download4 = {"You are downloading Audacity.zip."};<nitpick>
    Do you understand what arrays are for?
    </nitpick>

  • Missing return statement error! HOW?

    Why would the following code complain that it's missing a return statement, yet there are more than 4 return statements. All the possibilities are captured on the if statements and there are no more possibilities.
    public static double power(double b, int e)
            if(e == 0 || b == 1)
                return 1;
            else if(e > 0)
                if (b > 0)
                    return b * power(b, e - 1);
                else if (b % 2 == -1)
                    return -(power(b, -e));
            else if(e < 0)
                if(b > 0)
                    return 1 / power(b, -e);
                else if (b % 2 == 1)
                    return -(1 / power(b, -e));
        }Edited by: deyiengz on Jul 30, 2009 8:34 PM

    ejp,
    Thanks for the rapid response
    I thought there could only be these possibilities:
    1. e = 0 and b = 1
    captured in the 1st if statement
    2. e > 0 and either (b > 0 or b < 0)
    captured in the second if
    3. e < 0 and either (b > 0 or b < 0)
    captured in the Third if
    and else nothing else+
    What's remaining? This was meant to be easy, what the hell am I not seeing?
    flounder Thanks too for your response.
    I tried to remove the if on the last else if (below) but still got the error
    else
                if(b > 0)
                    return 1 / power(b, -e);
                else if (b % 2 == 1)
                    return -(1 / power(b, -e));
            }Edited by: deyiengz on Jul 30, 2009 9:14 PM

  • "Missing Return Statement" although the return statement IS there?

    Hello :) I am currently studying computing science at staffordshire university, java is one of my modules (first year) and im about half way through (still at introduction stage though)... Within my code apparently I have not returned a statement... yet to my believe the return statement is there and in the correct space, i would appreciate it if you could have a look and tell me where I am going wrong please:
    import java.util.*;
    public class ReadWriteArrayApp3
    +{+
    + public static void main(String [ ] args)+
    + {+
    + int[] nums = int double[6];+
    + double result;+
    + readArray(nums);+
    + printArray(nums);+
    + printReverse(nums);+
    + averageArray(nums);+
    result = averageArray(nums);
    + System.out.println("The average of your numbers is " + result);+
    + } // end main+
    public static void readArray(int [] a)
    + {+
    + Scanner kybd = new Scanner(System.in);+
    + System.out.println("Please enter 6 Integers");+
    + for(int i=0; i < a.length; i++)+
    + {+
    + a[i] = kybd.nextInt();+
    + }+
    + }+
    +public static void printArray(int [ ] b)+
    + {+
    + for (int i = 0; i < b.length; i++)+
    + {+
    + System.out.println(b);+
    + }+
    + }+
    + public static void printReverse(int [ ] c)+
    + {+
    + for (int i = c.length-1; i >= 0; i--)+
    + {+
    + System.out.println(c[i]);+
    + }+
    + }+
    + public static double averageArray(int [ ] d)+
    + {+
    + double sum, tot, average;+
    + for (int i = 0; i < d.length; i++)+
    + {+
    + tot = tot + d[i];+
    + average = (tot)/d.length;+
    + if ((average)=(tot/d.length))+
    + {+
    + sum = average;+
    +*  }
    + return sum;+
    + }+
    +} // end application class+
    Console states:
    javac  ReadWriteArrayApp3.java
    ReadWriteArrayApp3.java:49: missing return statement
    * ^*
    *1 error*
    Above in the code I have shown I have made a part bold... this shows the area in which console has a problem with.
    I would really appreciate any help in which I get
    Thankyou
    Victoria
    Edited by: StaffsUniJavaGirl on Nov 12, 2009 9:48 AM

    import java.util.*;
    public class ReadWriteArrayApp3
         public static void main(String [ ] args)
              int[] nums = int double[6];
              double result;
              readArray(nums);
              printArray(nums);     
              printReverse(nums);
              averageArray(nums);
              result = averageArray(nums);
              System.out.println("The average of your numbers is " + result);
         }  //  end main
         public static void readArray(int [] a)
              Scanner kybd = new Scanner(System.in);
              System.out.println("Please enter 6 Integers");
              for(int i=0; i < a.length; i++)
              a[i] = kybd.nextInt();
         public static void printArray(int [ ] b)
              for (int i = 0; i < b.length; i++)
                   System.out.println(b);
         public static void printReverse(int [ ] c)
              for (int i = c.length-1; i >= 0; i--)
                   System.out.println(c[i]);
         public static double averageArray(int [ ] d)
              double sum, tot, average;
              for (int i = 0; i < d.length; i++)
                   tot = tot + d[i];
                   average = (tot)/d.length;
                   if ((averagetot)=(tot/d.length))
                        sum = average;
         return sum;
    } // end application class*line 49 is bold*                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Missing return statement error

    public class Member
             public int Member(String memberid, String memberpw)
         String cs = "jdbc:oracle:thin:@255.255.255.255:1000:a123stud";
             String user = "123456";
             String pass = "123456";
              String member = "member_id";
             try
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   //Connection conn = DriverManager.getConnection("jdbc:odbc:myOracle");
                   Connection conn = DriverManager.getConnection(cs,user,pass);
                   Statement stmt = conn.createStatement();
                   String query = "SELECT * FROM members";
                   ResultSet rs = stmt.executeQuery(query);
                 // ResultSet rs = stmt.executeQuery("SELECT * FROM members WHERE member_id = 'M0001'");
                        int counter = 0;
                        while(rs.next())
                             member = rs.getString("member_id");
                             counter++;
                             if (counter == 0)
                             return 0;
                             else
                             return 1;
                        //System.out.println("\nOracle10g at 255.255.255.255 is working!");
              catch(SQLException e)
                   System.out.println("\n\nException Occured " +
                             "(Incorrect IP address, Server may be down, or SQL Exception)");
                   e.printStackTrace();
              catch(ClassNotFoundException e)
                   System.out.println("\n\nException Occured (CLASSNOTFOUND Exception)");
    }It says i am missing the return statement,but i do have set return something,whats the error? thx for helping

    For example, what happens if the SQL query doesn't
    return any rows, and rs.next() is never true?The while() loop will be skipped and the if statement
    will execute, which has two branches, one of which is
    guaranteed to return?Oops. My bad.
    I thought the ifs were inside the while.
    Okay, the problem here is with the exception handling. Catching and logging and doing nothing else is usually almost as bad as just smothering them. In this case it's especially true because the method then just continues after the catch blocks, in which case there's no return.
    You have to actually handle the exceptions if you're not going to propagate them. In this case, that would mean returning some reasonable default value. I'd say that's not a good idea here, and you're better off to just let the exceptions be thrown, or wrap and rethrow in your own exception.

  • Missing return statement?  News to me!

    Before I ask anything let be begin by saying thanks to all you people that help others on these boards, I've never posted a question before but I have often found the answers to my problems somewhere here. I'm currently working on one of my last java assignments ever and I am completely stumped as to whats going on. All I want out of this code is for it to read a txt file for a bunch of phone book entries, load them into some arrays, then sort them by first name, last name, then phone# then return the array so I can use it later on. I've got the entries loaded, I've got em sorted, but I can;t return it. When I try I get a missing return statement error. I dont know why its not returning the array, so I thought I'd ask the pros. I can get it to work fine if I dont return anything but what good is that eh?
    Please forgive my terrible coding, I am in no way a real programmer, I just want to pass my classs and never think about it again 8) any help would be appreciated. Tis is built to work with an "Entry" file, if you guys need it to proceed lemme know and I will post it. Thanks.
    the code....
        public class CSCD210PhoneBook {
           public static void main(String[] args)throws IOException
          {//Opening main          
             Scanner kb = new Scanner(System.in);
               int entryCount=0;
                   Scanner fileScanner=null;
                   Entry[] array=null;
         array=populateEntry(entryCount, fileScanner, kb);
          }//end main array=
                 public static  Entry[] populateEntry(int entryCount, Scanner fileScanner,Scanner kb)throws IOException
                    int lineCount=0;
                   String fileName;
                   File fileHandle;     
                   System.out.println("Which file would you like your entries pulled from?");
                   fileName= kb.nextLine();
                               fileHandle = new File(fileName);
                   fileScanner = new Scanner(fileHandle);
                   while(fileScanner.hasNext())
                         fileScanner.nextLine();
                         lineCount++;
                   entryCount= lineCount/8;
                   Entry[] array=new Entry[entryCount];
                   fileScanner.close();
                   fileHandle = new File(fileName);
                   fileScanner = new Scanner(fileHandle);
                        for(int i =0; i<array.length;i++)
                             array=new Entry(fileScanner);
                   fileScanner.close();
                   int curPos, indexSmallest, start;
    Entry temp;
    for (start = 0; start < array.length - 1; start++)
    indexSmallest = start;
    for (curPos = start + 1; curPos < array.length; curPos++)
    if (array[indexSmallest].compareTo(array[curPos]) > 0)
    indexSmallest = curPos;
    } // end for
    temp = array[start];
    array[start] = array[indexSmallest];
    array[indexSmallest] = temp;
                   return array;
    Any help would be most appreciated.

    The code you posted has mismatched braces: it needs another } at the end.
    Linked with this is how - or rather when - you return array from the populateEntry()
    method. You have a couple of nested for-loops and you return array inside (at the
    end of) the outer loop.
    The compiler is really fussy about making sure that an Entry[] is returned from this
    method. If you outer for-loop never gets executed for some reason, then the return
    statement will never be reached. The compiler won't accept this.
    Either
    (1) move the return statement outside both loops so it is always executed. This
    appears to be the most logical thing - but I haven't read your code that closely. It's
    just that having return at the end of a for-loop (with no "continue" in sight), doesn't
    make a lot of sense.
    or
    (2) add another return after both loops have finished.

Maybe you are looking for

  • Reversing PGI without cancelling Excise Invoice

    Hi, Is there any process where we can Reverse PGI without cancelling the Commercial Invoice & Excise Invoice and again connecting the same corrected delivery to the old invoice number. To be more clear, in delivery if I have picked a wrong batch numb

  • What is my serial number?

    I recenetly purchased and installed Logic 9 Pro from the app store, and now it is asking for my serial number which I never got... Also this is a newe computer and I have never had logic on it before.

  • Jquery - Detect Page / Item Change

    Hi Guys, I am aware of the skillbuilders save before exit plugin but I was wondering if there is a stripped down version, maybe some Jquery to identify if a Page has had any changes made. For example if an item on a page is accessed / changed in anyw

  • PIRs not shown in MD04

    Hi Experts, I have created Planned Independent Requirements (PIR) to the material but which are not reflected in Stock Requirement List (MD04).  What could be the reasons? Best answers will be rewarded. Thanks & Regards, Surya 9000440032

  • Recovered deleted iPhoto library is in wrong format?

    My iPhoto library was deleted so I used Disk Drill Pro and seemingly successfully recovered them. I recovered them and saved them to a USB drive but when I click the recovered library, iPhoto says it doesn't recognize the format. This is what the con