Populating an ArrayList of ArrayList

Hi,
Could anyone pls help me with this one. I'm trying with the following code to populate an ArrayList (alDataRows) which contain several ArrayLists(alCols). variable rsResultSet is the resultset from which I want to populate this arraylist and variable intNumberOfColumns is the number of columns I have in that resultset.
What's happening is that, finally, I'm getting the last record only in this arraylist. Also, if I don't do alCols.clear(), alCols is having (number of columns * number of rows) records which is erroneous.
Could somebody pls correct me.
thanks much in advance!
=====================
ArrayList alCols = new ArrayList();
ArrayList alDataRows = new ArrayList();
int intRowPos = 0;
while (rsResultSet.next())
alCols.clear();
for (int i=0; i < intNumberOfColumns ; i++)
     alCols.add(i, rsResultSet.getString(i+1));
alDataRows.add(intRowPos,alCols);
intRowPos++;
//System.out.println("intRowPos = " +intRowPos);
}

Could anybody pls help me on this one?
I have the following to populate an arrylist(alDataRows) of arraylists(alCols).
ArrayList alCols = null;
ArrayList alDataRows = new ArrayList();
int intRowPos = 0;
while (rsResultSet.next())
alCols = new ArrayList();
for (int i=0; i < intNumberOfColumns ; i++)
{      alCols.add(i, rsResultSet.getString(i+1));  
alDataRows.add(intRowPos,alCols);
intRowPos++;
Now how do I retrieve a particular value within it?
Is it like (String)alDataRows.get(rowindex).get(colindex).
This is not compiling.
thanks much

Similar Messages

  • Populating an arraylist

    hi Everyone,
    I am finding it difficult to write this code....Can anyone help me out
    i have a DVDInfo.text file which contains the following text
    Donnie Darko/sci-fi/Gyllenhall, Jake
    Raiders of the Lost Ark/action/Ford, Harrison
    2001/sci-fi/??
    Caddy Shack/comedy/Murray, Bill
    Star Wars/sci-fi/Ford, Harrison
    Lost in Translation/comedy/Murray, Bill
    Patriot Games/action/Ford, Harrison
    I have created a BufferedReaderObject to read from the file.
    Then after i read the data from the text file i make use of String.split() to parse that line of data.
    But the main prablem is i am unable to give these values to the DVDInfo's instance members
    DVDInfo class is
    class DVDInfo
    String title;
    String genre;
    String leadActor;
    DVDInfo(String t, String g, String a)
    title = t; genre = g; leadActor = a;
    public String toString()
    return title + " " + genre + " " + leadActor + "\n";
    public String getTitle()
         return title;
    public String getGenre()
         return genre;
    public String getLeadActor()
         return leadActor;
    public void setTitle(String title)
         this.title = title;
    public void setGenre(String genre)
         this.genre = genre;
    public void setLeadActor(String leadActor)
         this.leadActor = leadActor;
    // getters and setter go here
    public class DVDInfoClass
         public static void main(String args[])
              String s1;
              String s2;
              String s3;
              BufferedReader fr = new BufferedReader(new FileReader("DVDInfo.txt"));
              s1 = fr.readLine();
    So how do i populate DVDInfo's three instance variables.
    Then finally i want to put all of the DVDInfo instances into an ArrayList
    Thanks in advance
    Deepthi

    I hope this code will solve your problem
    import java.io.*;
    import java.util.*;
    public class ReadDVDFile
        String MName;
         String Gener;
         String Actor;
         ReadDVDFile(String m, String g, String a){
              MName = m;
               Gener = g;
               Actor = a;
         public static void main(String[] args){
                ArrayList al = new ArrayList();
         try{
            File dvd = new File("e:\\DVDInfo.txt");
            BufferedReader br = new BufferedReader(new FileReader(dvd));
            String s;
            while((s = br.readLine()) != null){
            String[] result = s.split("/");
               al.add(new ReadDVDFile(result[0],result[1],result[2]));
              }  // end of while
         catch(Exception e){
               System.out.println(e);
           Iterator i = al.iterator();
           int j = 1;
            System.out.println("printing contents of ArrayList");
            while(i.hasNext()){
                 ReadDVDFile rd = (ReadDVDFile) i.next();
              System.out.println(j + " " + rd.MName + ";" + rd.Gener + ";" + rd.Actor );
               j++;
    }

  • Use of Generics in ArrayList now mandatory?

    Hi,
    I'm writing a little Applet involving the population of ArrayList (my Java compiler is version 1.6.0_22).
    My code is similar to
    ArrayList vertexPoints = new ArrayList();
    - it compiles OK, but when I try and run the applet, it falls out saying that there is a NullPointerException in the above line. I was under the impression that the use of generics in ArrayLists is not compulsory? Or will I have to
    change the code to something like
    ArrayList<3DPoint> vertexPoints = new ArrayList<3DPoint>():
    Some websites with tutorials give the impression that providing a type is optional, hence my confusion.

    799615 wrote:
    but accessing a method of an array of objects. I'll soldier on....Since you have not provided any more information we can only make educated guesses. Perhaps you are doing something like:
    Foo[] fooList = new Foo[5];
    fooList[0].doStuff(); // NullPointerExceptionWhy? The first line only creates an array. It does not automagically create any Foo objects for you. Therefore the array is full of the deafult value and for Objects (reference types) it is null. So effectively the second line is null.doStuff().

  • How to use ArrayList to represent muti-dimension array?

    For example, how to use ArralyList to represent array likes this:
    a[0][0] = xxx
    a[1][1] = xxx
    a[2][2] = xxx
    .....Thanks

    For example, how to use ArralyList to represent array likes this:
    > a[0][0] = xxx
    a[1][1] = xxx
    a[2][2] = xxx
    .....Use an ArrayList populated with ArrayLists?
    kind regards,
    Jos

  • ArrayList Population in JTable

    I have a jtable built using AbstractTableModel. I want to populate the tabe using an arraylist but do not know how to go about it. I know I need to override public Object getValueAt(int row, int column) method.
    Can anyone guide me on this?

    Have a look at Rob Camick's [Row TableModel |http://tips4java.wordpress.com/2008/11/21/row-table-model].
    And his other Model classes too.
    Have a look at [this thread|http://forums.sun.com/thread.jspa?forumID=57&threadID=5373299] for design considerations.
    Jerome
    P.S.: note that unless you use a handy subclass such as Rob's ones, you'd have to override the getValueAt(int row, int column) method and all the other abstract methods of AbstractTableModel (check the Javadoc).
    P.P.S.: more seriously, have a look at the API Javadoc in general, most often it pays back.
    Edited by: jduprez on Nov 19, 2009 1:05 PM

  • I am currently having trouble with an attached PDF fill-able form...Help Please

    Hello, I was wondering if you would be able to help me out?
    I am having trouble with my attached PDF fill-able form, I am creating a form that has a limit of one page so in order for more room in a certain field I have added a Hyperlink to an additional fill-able(secondary) form within the Parent document (primary fill-able form. The secondary form is inserted as an attachment into the Primary form. My problem is when I open this document up in Adobe Reader, the Primary fill-able form is savable but the attached Secondary form for which the hyperlink leads to is non-savable and is a must print only. Is there a way to make the Secondary form savable as well within the same document? or is there another way I could execute what it is I am trying to achieve?
    Help would be greatly appreciated please and thank you!

    Here is the code, thought I had put it in the first time, guess not heh. Anyway, I converted the arrayList(accountList) to a String so that I could see the that element I am trying to index is in there, which it is. I also checked the file that i'm populating the arrayList from and it also has the element in it.
    public static void getAccountNumbers() {
              accountList = LoadStoreAccounts.readCollectionObject();     
              accountInfo = accountList.toString();
              JOptionPane.showMessageDialog(null, accountInfo);
              acctNumIndex = accountList.indexOf(accountNumber);
              acctIndex = String.valueOf(acctNumIndex);
              JOptionPane.showMessageDialog(null, "Index of accountNumber    is: " + acctIndex);

  • How to get result of querry independet of a datatype?

    Hi All!
    I try to write a program, that calls stored procedures in a database independent of a name and arguments list. To get a result of a query I must call one of the functions getInt(), getString() etc. of CallableStatement. I'd like to write a wrap function, for instance getResult(), that get the result independent of the result's type. Has anybody any idea, how I can do it?
    Any help will be appreciate.
    Regards,
    Andrej.

    Hi Justin,
    Even we have been writing a kind of these generic methods to send a query to database, fetch the Resultset and then populate an ArrayList with the Resultset data.
    What do you get out of this ?
    -> Less code to maintain
    -> Single point of access to datasource
    -> JDBC Code reuse
    i agree that it might cost some cpu cycles in populating an ArrayList and then doing the casting again. But isn't it worth all the above credits.
    An example of such a method is
      public ArrayList execute( String query, ArrayList params )
                    throws SQLException {
        Connection con = null; // Database Connection object
        ArrayList rowset = new ArrayList();
        try {
          // Get the Database Connection
          con = connector.getConnection();
          // Use PreparedStatement object to execute the SQL Query
          PreparedStatement pst = con.prepareStatement( query );
          // Bind the columns values from the ArrayList object
          if( params != null ) {
            for( int i = 0; i < params.size(); i++ ) {
              pst.setObject( i + 1, params.get( i ) );
          // Execute the Query to get the ResultSet object
          ResultSet rst = pst.executeQuery();
          // Get column count from ResultSet Metadata
          int colCount = rsmtdt.getColumnCount();  // This may not be the correct syntax
          // Populate ArrayList
          while(rset.next()) {
            ArrayList row = new ArrayList();
         for(int i=1;i<=colCount;i++)
           row.add(rset.getObject(i);
         rowset.add(row);
          // Close the ResultSet and Statement
          rst.close();
          pst.close();
        } catch( SQLException ex ) {
          throw new DBException( "Unable to execute the SQL Query in execute "+
                                     "method of DBBroker class of given status " +
                                 " : " + ex.getMessage() );
        } catch( Exception ex ) {
          throw new DBException( "Exception thrown in execute() method of " +
                                 "DBBroker class of given status : " +
                                  ex.getMessage() );
        } finally {
          try {
            connector.releaseConnection( con ); // Releases the connection
          } catch( DBConException ex ) {
            throw new DBException( "Unable to release the connection of given " +
                                   "status : " + ex.getMessage() );
        return rowset;
      }Regards
    Elango.

  • How to call a method on click of selectOneChoice dropdown box

    Hi,
    I am using selectOnceChoice whose list is coming from an arrayList.
    On the load of my page, I am populating the arrayList and it is getting visible in the selectOneChoice dropdown.
    But I have a scenario where I need to populate the arrayList(List Items) for selectOnceChoice on click of selectOnceChoice box. Not at the time of page load.
    I tried to do that with the help of clientListener and ServerListener but it seems that it is ServerListener is not the child attribute of selectOnceChoice.
    Can anyone please help me out to perform or call a method on click of selectOnceChoice box.
    Thanks,
    Vicky

    Could someone please explain to me the main difference between adapters and listeners? WindowListener is an interface, if you use it then you have to implement all its methos whether you use then or not while WindowAdapter is a class which implements WindowListener and provides empty implementations of all the methods in the listener, so basically by using windowAdapter you are avoiding
    the implementation of methods which you don't required.

  • Display of dynamic data in Listbox in jsp usin Struts

    Hi,
    I am trying to display a List in a jsp in Struts.
    I have written a Action form and am populating a Arraylist in a DAO(java class file).
    ArrayList.add(rs.getString(1),rs.getSTring(2));
    But I do not know how to display the arraylist in JSP using the struts tag libraries.
    Please let me know how this can be done.
    Thanks in advance.
    Sri

    Use logic:iterate or nested:iterate.
    You can refer to:
    http://forum.java.sun.com/thread.jspa?threadID=5164152&messageID=9629275#9629275
    http://struts.apache.org/1.x/struts-taglib/tlddoc/index.html
    SirG

  • Unable to show JSF dropdown with a list containing custom beans

    Hi,
    Please help me with my problem guys.
    In the JSF Portlet application that Iam currently working, I need to show some dropdowns,so I am passing arraylist in my JSP like this:
    <code]
    <f:view>
    <hx:scriptCollector id="scriptCollector1">
    <h:form styleClass="form" id="form1"><P>Place content here.
    <h:selectOneMenu styleClass="selectOneMenu" id="menu1" >
    <f:selectItems value="#{gfogBean.northAmericaList.toArray}"/>
    </h:selectOneMenu>
    </h:form>
    </hx:scriptCollector>
    </f:view>
    gfgoBean is my FacesManagedBean, northAmericaList has objects of type TestBean....
    public class GfogBean {
         private String exchangeEurope;
         private String exchangeAsiaPacific;
         private String exchangeNorthAmerica;
         private List northAmericaList = new ArrayList();
          * @return Returns the northAmericaList.
         public List getNorthAmericaList() {
              northAmericaList.add(new TestBean("north","north"));
              return northAmericaList;
          * @param northAmericaList The northAmericaList to set.
         public void setNorthAmericaList(List northAmericaList) {
              this.northAmericaList = northAmericaList;
          * @return Returns the exchangeAsiaPacific.
         public String getExchangeAsiaPacific() {
              return exchangeAsiaPacific;
          * @param exchangeAsiaPacific The exchangeAsiaPacific to set.
         public void setExchangeAsiaPacific(String exchangeAsiaPacific) {
              this.exchangeAsiaPacific = exchangeAsiaPacific;
          * @return Returns the exchangeEurope.
         public String getExchangeEurope() {
              return exchangeEurope;
          * @param exchangeEurope The exchangeEurope to set.
         public void setExchangeEurope(String exchangeEurope) {
              this.exchangeEurope = exchangeEurope;
          * @return Returns the exchangeNorthAmerica.
         public String getExchangeNorthAmerica() {
              return exchangeNorthAmerica;
          * @param exchangeNorthAmerica The exchangeNorthAmerica to set.
         public void setExchangeNorthAmerica(String exchangeNorthAmerica) {
              this.exchangeNorthAmerica = exchangeNorthAmerica;
    }But I am getting this exception.
    Nested Exception is javax.servlet.jsp.JspException: javax.faces.el.ReferenceSyntaxException: The "." operator was supplied with an index value of type "java.lang.String" to be applied to a List or array, but that value cannot be converted to an integer.
         at com.sun.faces.taglib.html_basic.SelectOneMenuTag.doEndTag(SelectOneMenuTag.java:483)
         at org.apache.jsp._GfogWeb._jspService(_GfogWeb.java:220)
         at com.ibm.ws.webcontainer.jsp.runtime.HttpJspBase.service(HttpJspBase.java:89)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:344)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.serviceJspFile(JspServlet.java:683)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:781)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1049)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:600)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:254)
         at org.apache.pluto.core.impl.PortletRequestDispatcherImpl.include(PortletRequestDispatcherImpl.java:112)
         at com.ibm.faces.context.PortletExternalContextImpl.dispatch(PortletExternalContextImpl.java:439)
         at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:295)
         at com.ibm.faces.application.PortletViewHandlerImpl.renderView(PortletViewHandlerImpl.java:74)
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
         at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:217)
         at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
         at com.ibm.faces.webapp.FacesGenericPortlet.doRender(FacesGenericPortlet.java:358)
         at com.ibm.faces.webapp.FacesGenericPortlet.doView(FacesGenericPortlet.java:389)
         at com.jpmorgan.gfogwebportlet.portlet.GfogInitPortlet.doView(GfogInitPortlet.java:51)
         at com.ibm.faces.webapp.FacesGenericPortlet.doDispatch(FacesGenericPortlet.java:290)
         at javax.portlet.GenericPortlet.render(GenericPortlet.java:163)
         at com.ibm.wps.pe.pc.std.cmpf.impl.PortletFilterChainImpl.render(PortletFilterChainImpl.java:144)
         at com.ibm.wps.pe.pc.std.invoker.impl.PortletServlet.dispatch(PortletServlet.java:131)
         at com.ibm.wps.pe.pc.std.invoker.impl.PortletServlet.doGet(PortletServlet.java:70)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at com.ibm.wps.pe.pc.std.cache.CacheablePortlet.service(CacheablePortlet.java:256)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1049)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:600)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:254)
         at com.ibm.wps.pe.pc.std.invoker.impl.PortletInvokerImpl.invoke(PortletInvokerImpl.java:204)
         at com.ibm.wps.pe.pc.std.invoker.impl.PortletInvokerImpl.invoke(PortletInvokerImpl.java:168)
         at com.ibm.wps.pe.pc.std.invoker.impl.PortletInvokerImpl.render(PortletInvokerImpl.java:97)
         at com.ibm.wps.pe.pc.std.PortletContainerImpl.renderPortlet(PortletContainerImpl.java:110)
         at com.ibm.wps.pe.pc.PortletContainerImpl.doRenderPortlet(PortletContainerImpl.java:545)
         at com.ibm.wps.pe.ext.render.AbstractRenderManager.performService(AbstractRenderManager.java:251)
         at com.ibm.wps.pe.pc.PortletContainerImpl.renderPortlet(PortletContainerImpl.java:100)
         at com.ibm.wps.engine.tags.PortletRenderTag.doStartTag(PortletRenderTag.java:155)
         at org.apache.jsp._Control._jspService(Control.jsp  :176)
         at com.ibm.ws.webcontainer.jsp.runtime.HttpJspBase.service(HttpJspBase.java:89)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:344)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.serviceJspFile(JspServlet.java:683)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:781)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.ServicingServletState.service(StrictLifecycleServlet.java:333)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1044)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:600)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:254)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.handleRequest(DispatcherServiceImpl.java:89)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.include(DispatcherServiceImpl.java:50)
         at com.ibm.wps.services.dispatcher.Dispatcher.include(Dispatcher.java:44)
         at com.ibm.wps.engine.templates.skins.Default.render(Default.java:74)
         at com.ibm.wps.engine.templates.SkinTemplate.render(SkinTemplate.java:71)
         at com.ibm.wps.composition.elements.Component.render(Component.java:785)
         at com.ibm.wps.composition.elements.Control.render(Control.java:182)
         at com.ibm.wps.composition.Composition.render(Composition.java:2880)
         at com.ibm.wps.model.wrappers.LayoutModelWrapperFactoryImpl$LayoutModelWrapperImpl.render(LayoutModelWrapperFactoryImpl.java:204)
         at com.ibm.wps.model.ModelUtil$WrappedCompositionModel.render(ModelUtil.java:832)
         at org.apache.jsp._UnlayeredContainer_2D_V._jspService(UnlayeredContainer-V.jsp     :11)
         at com.ibm.ws.webcontainer.jsp.runtime.HttpJspBase.service(HttpJspBase.java:89)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:344)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.serviceJspFile(JspServlet.java:683)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:781)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.ServicingServletState.service(StrictLifecycleServlet.java:333)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1044)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:600)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:254)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.handleRequest(DispatcherServiceImpl.java:89)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.include(DispatcherServiceImpl.java:50)
         at com.ibm.wps.services.dispatcher.Dispatcher.include(Dispatcher.java:44)
         at com.ibm.wps.engine.templates.skins.Default.render(Default.java:74)
         at com.ibm.wps.engine.templates.SkinTemplate.render(SkinTemplate.java:71)
         at com.ibm.wps.composition.elements.Component.render(Component.java:785)
         at com.ibm.wps.composition.Composition.render(Composition.java:2880)
         at com.ibm.wps.model.wrappers.LayoutModelWrapperFactoryImpl$LayoutModelWrapperImpl.render(LayoutModelWrapperFactoryImpl.java:204)
         at com.ibm.wps.engine.tags2.PageRenderTag.doStartTag(PageRenderTag.java:397)
         at org.apache.jsp._Home._jspService(Home.jsp  :15)
         at com.ibm.ws.webcontainer.jsp.runtime.HttpJspBase.service(HttpJspBase.java:89)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:344)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.serviceJspFile(JspServlet.java:683)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:781)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.ServicingServletState.service(StrictLifecycleServlet.java:333)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1044)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:600)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:254)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.handleRequest(DispatcherServiceImpl.java:89)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.include(DispatcherServiceImpl.java:50)
         at com.ibm.wps.services.dispatcher.Dispatcher.include(Dispatcher.java:44)
         at com.ibm.wps.engine.templates.screens.Default.render(Default.java:91)
         at com.ibm.wps.engine.templates.ScreenTemplate.render(ScreenTemplate.java:61)
         at com.ibm.wps.engine.tags2.ScreenRenderTag.doStartTag(ScreenRenderTag.java:89)
         at org.apache.jsp._Default._jspService(Default.jsp  :768)
         at com.ibm.ws.webcontainer.jsp.runtime.HttpJspBase.service(HttpJspBase.java:89)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:344)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.serviceJspFile(JspServlet.java:683)
         at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:781)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1044)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:600)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:254)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.handleRequest(DispatcherServiceImpl.java:89)
         at com.ibm.wps.services.dispatcher.DispatcherServiceImpl.include(DispatcherServiceImpl.java:50)
         at com.ibm.wps.services.dispatcher.Dispatcher.include(Dispatcher.java:44)
         at com.ibm.wps.engine.templates.themes.Default.render(Default.java:103)
         at com.ibm.wps.engine.templates.ThemeTemplate.render(ThemeTemplate.java:67)
         at com.ibm.wps.engine.phases.WPRenderPhase.processRendering(WPRenderPhase.java:312)
         at com.ibm.wps.engine.phases.WPRenderPhase.execute(WPRenderPhase.java:135)
         at com.ibm.wps.state.phases.AbstractRenderPhase.next(AbstractRenderPhase.java:106)
         at com.ibm.wps.engine.phases.WPAbstractRenderPhase.next(WPAbstractRenderPhase.java:93)
         at com.ibm.wps.engine.Servlet.callPortal(Servlet.java:713)
         at com.ibm.wps.engine.Servlet.doGet(Servlet.java:562)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:76)
         at com.ibm.wps.state.filter.StateCleanup.doFilter(StateCleanup.java:86)
         at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:132)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:71)
         at com.ibm.wps.mappingurl.impl.URLAnalyzer.doFilter(URLAnalyzer.java:216)
         at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:132)
         at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:71)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1040)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:600)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:201)
         at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:125)
         at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:286)
         at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71)
         at com.ibm.ws.webcontainer.cache.invocation.CacheableInvocationContext.invoke(CacheableInvocationContext.java:116)
         at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:186)
         at com.ibm.ws.webcontainer.oselistener.OSEListenerDispatcher.service(OSEListener.java:334)
         at com.ibm.ws.webcontainer.http.HttpConnection.handleRequest(HttpConnection.java:56)
         at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:624)
         at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:458)
         at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:912)Then I changed the <f:selectItems/> little bit like
    <f:selectItems value="#selectItems.gfogBean.northAmericaList.toArray}"/>Then there was no error ,but the dropdown was null.
    Again I modifed the <f:selectItems/> tag in this way:
    <f:selectItems value="#{selectitems.gfogBean.northAmericaList.testBeanValue.testBeanValue.toArray}"/>then the dropdown appeared but the values were showing up twice.
    Can anybody give me solution to this problem.Even a custom converter or a custom component could solve this problem.. \n
    Because in my application, we are not populating the arraylists with SelectItem type.

    The perInfoAll list should be declared locally in getPerInfoAll(), otherwise it grows every time you call it.
    #{e.id};Remove the semicolon, unless you want to see it on the page, which doesn't seem right. Try <h:outputText value="#{e.id}"/> instead. Only certain types of children are supported inside h:column.

  • GA Help Needed Urgently

    Hi,
    I'm stuck on how exactly to define the selectParent() method (the Selection method) because I have to take out samples of size 5 (the tournament size) from the population and then order those chromosomes ( in the contenders ArrayList) in order of fitness (the lower the fitness the better). But since I'm working with ArrayLists and since I have to extract each Chromosome object from the contender Arraylist, somehow call the fitness() method on each Chromosome, and then sort in order of fitness (lowest first), then store the 2 Chromosomes with the lowest fitness into a parent ArrayList, I'm lost with how to do this. Any ideas on this please? What's the simplest way of doing it?
    Here's the code I have done - the commented stuff is the stuff I have tried to code to do the sorting, but it's all useless now. I am almost in a giving up situation here - Can anyone come up with a solution for how the tournament selection sort would be done in order for my code to run - or some sort of sorting algorithm to order the fitness from lowest to highest as this is the part I am find most trouble with - the thing I don't understand is that because the fitness value of each Chromosome is not stored anywhere (like a variable or ArrayList), how am I able to order the fitnesses from every sample of 5? PLEASE HELP URGENTLY :-(
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Collections;
    import java.math.*;
    import java.util.Collection;
    class Population {
      Database d = new Database();
      Random rand = new Random();
      ArrayList population = new ArrayList();
      ArrayList parents = new ArrayList();
      ArrayList contenders = new ArrayList();
      public void initialPopulation() {
        double[] reuters = {
            8.0, 9.0, 12.5, 11.5, 6, 7, 4, 2, 3, 4, 3, 5, 5.5};
        Share s1 = new Share(reuters);
        d.addShare(s1);
        for (int i = 0; i < 10; i++) {
          Chromosome c = new Chromosome(rand);
          c.setDatabase(d);
          population.add(c);
          System.out.println("Chromosome Weights are: " + c);
          System.out.println("Chromosome Fitness Value is: " + c.fitness(0));
          System.out.println();
        System.out.println(population.size());
        System.out.println(population.toString());
        System.out.println();
    //     System.out.println(d);
      public ArrayList selectParents(int tournamentSize) {
        // Get as many chromosomes as specified by tournament size
        for (int i = 0; i < tournamentSize; i++) {
          contenders.add(i, population.get(i));
        // Sort the sub-population in order of fitness *****Having Huge Problems Here***
      /*  double[] fitnessVals = new double[5];
        double[] temp = new double[5];
        ArrayList tempArrayList = new ArrayList();
        for (int i = 0; i < (contenders.size()); i++) {
          Chromosome temp1 = (Chromosome)contenders.get(i);
          fitnessVals[i] = temp1.fitness(0); }
    System.out.println((fitnessVals[0]) +","+ (fitnessVals[1]));
       for (int i = 0; i < (contenders.size()); i++) {
        if (fitnessVals[i] > fitnessVals[i+1])
          temp[i] = fitnessVals[i + 1];
          fitnessVals[i + 1] = fitnessVals;
    fitnessVals[i] = temp[i];
    tempArrayList.add(contenders.get(i + 1));
    contenders.set(i+1, contenders.get(i));
    contenders.set(i, tempArrayList.get(i));
    else {}
    // Collections.max((Collection)contenders.get(0));
    // System.out.println(contenders.toString());
    /* public void sortInOrderOfFitness(Comparable ArrayList ) {
    for (int i = 0; i < contenders.size(); i++) {
    Collections.sort(contenders);
    System.out.println(contenders); ****Up to Here is Where I'm Lost***
    // Return the best two
    parents.add(contenders.get(0));
    parents.add(contenders.get(1));
    System.out.println(parents.toString());
    System.out.println(contenders.toString());
    return parents;
    public static void main(String args[]) {
    Population p = new Population();
    p.initialPopulation();
    p.selectParents(5);
    import java.util.ArrayList;
    import java.util.Random;
    class Chromosome
    { int[] bit = new int[12];
    Database db;
    Chromosome(Random rand)
    { for (int i = 0; i < 12; i++)
    { bit[i] = rand.nextInt(6); }
    public String toString()
    { String res = "";
    for (int i = 0; i < 12; i++)
    { res = res + bit[i] + ","; }
    return res;
    public void setDatabase(Database d)
    { db = d; }
    public double fitness(int share)
    { double prediction = 0;
    int divisor = 0;
    Share sh = db.getShare(share);
    for (int i = 0; i < 12; i++)
    { prediction = prediction + bit[i]*sh.getPrice(i);
    divisor = divisor + bit[i];
    if (divisor != 0)
    { prediction = prediction/divisor; }
    else
    { prediction = 0; }
    System.out.println("Prediction Value is: " + prediction);
    double actualPrice = sh.getPrice(12);
    return Math.abs(prediction - actualPrice);
    import java.util.ArrayList;
    import java.util.Random;
    class Database
    { ArrayList sharedata = new ArrayList();
    public void addShare(Share s)
    { sharedata.add(s); }
    public Share getShare(int i)
    { return (Share) sharedata.get(i); }
    class Share
    { double[] prices = new double[13];
    Share(double[] p)
    { prices = p; }
    double getPrice(int i)
    { return prices[i]; }

    No you're not I'm still hereI was making a point that it's rude to flag your
    questions as urgent. As you can see, a lot of the
    people who answer questions tend to ignore such
    posts.
    I didn't realise this until now since you've pointed it out - I saw other posts with 'urgent' and felt mine really was urgent which is why I did this.
    >
    , any ideas??Yes, throw that commented method away and read up on
    how to use Java's collections API to properly sort a
    list/collection of objects:
    http://java.sun.com/docs/books/tutorial/collections/in
    terfaces/order.html
    Good luck.I'm going to have a good look at this now. Hopefully I'll be able to get somewhere.

  • Data table vanishing on reload

    Hi,
    I have in the jsp a table populated by arraylist. The bean used is request scope and cannot be kept as session scope. When I view the page for the first time the list comes properly. But subsequent operation on the same page the list doesnt appears. On subsequent opertaion I dont repopulate because I think jsf should do the same for me.
    Could anyone help me on this?
    Regards,
    KP

    I have seen similar behavior when nested collections are used to populate nested datatables and the bean had a scope of request. Outside those nested cases, I did not experience the behavior you are describing with request bean. I think it is a bug. Use session scope as a workaround. Unfortunately you will need to manually remove from session scope in case needed for performance reasons, ...etc

  • PLEASE HELP ME. THIS PROGRAM IS KILLING ME.

    Hi. I am getting so sick of this program. I have been trying to do it for the past couple of weeks and I am getting nowhere. I really wish someone can help me on it ... like totaly help me on it. I am getting so frustrated. I would appreciate all the help.
    This is the program:
    In Belageusia, a plorg has these properties:
    Data:
         A plorg has a name
         A plorg has a contentment index (CI), which is an integer between 0 and 100
    The population of plorgs in Belagersia is further subdivided into three mutually exclusive classes: Plebeians, Equidians, and Elitians.
    A Plorg?s stature is completely determined by their contentment index and witht that designation comes certain burdens and/or advantages.
    Plebeians have a contentment index in [0, 24].
    Each new Plebeian is welcomed with a contentment index of 2 and burdened with a debt of $10.00
    Plebeians never manage to break even, so they have no taxes imposed upon them. Furthermore, since they can never get out debt, they cannot accumulate any wealth.
    Equidians have a contentment index in [25, 75]
    Each new Equidian is welcomed with a contentment index of 50 and burdened with taxes of $20.00
    Equidians have taxes imposed upon them. Furthermore, since they do manage to break even, they have no debt. However, since they only manager to break even, they do not accumulate any wealth.
    Elitians have a contentment index in [76, 100]
    Each new Elitian is welcomed with a contentment index of 87 and burdened with taxes of $20.00, but also provided with a ?silver spoon? of $30.00 in accumulated wealth.
    Elitians manage to expand upon their wealth, sot hey have taxes imposed upon them. Furthermore, since they are accumulating wealth, they have no debt.
    At each interim time epoch the population of Belageusia retracts with a death rate randomly selected between 0% and 10%. If a plorg survives the purge, they have an opportunity to move one class higher and/or one class lower. However, remember that a plorg?s name is final. It never changes.
    For Plebeians this is transition is determined by randomly selecting a CI in [0, 49]. If this new CI is les than 25 then the plorg remains a Plebeian, with this newly assigned CI, and their debt increases 3.7%. If this new CI is in [25, 49], the Plebeian ascends to a Equidian, with this newly assigned CI, their debt is forgiven, but taxes of $20 are assessed.
    For Equidians this is determined by randomly selecting a CI in [0,100].
    If this new CI is in [25, 75] then the plorg remains a Equidian, with this newly assigned CI, but their taxes are increased 6.1%.
    If this new CI is in [0, 24] then the plorg becomes a Plebeian, with this newly assigned CI, their taxes are forgiven, but they are burdened with a debt of $10.00.
    If this new CI is in [76, 100] then the plorg becomes a Plebeian, with this newly assigned CI, but their taxes are increased 6.1%. However, they are bewtowed a wealth of $30.00.
    For Eletians this is determined by randomly selecting a CI in [51, 100]. If this new CI is greater than 76 then the plorg remains an Eletian, with this newly assigned CI, their taxes increase 6.1% and their wealth increases 4.9%. If this new CI is in [51, 75], then this plorg becomes an Equidian, with this newly assigned CI, their wealth is eliminated, and their taxes are increased 6.1%.
    At each time epoch, the population of Belageusia at a birth rate randomly selected between 0% and 10%. A randomly chosen number between 0-100 determines each newly born plorg?s stature. If this random number is in the range 0-24, create a new Plebeian. In the range 25-75, create a new Equidian, and if in the range 76-100, create a new Elitian.
    We are supposed to output the population characteristics of Belageusia, after 1000 time epochs.
    This is the code that I wrote down but got no where with:
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    public class Belageusiaplorg
         public static void main (String[] args)
              ArrayList Plebs = new ArrayList(350);
              ArrayList Equids = new ArrayList(600);
              ArrayList Elits = new ArrayList(350);
              ArrayList Holding = new ArrayList(600);
              for (int i=0; i<25; i++)
                   Plebs.add(new plebian());
              for (int i=0; i<50; i++)
                   Equids.add(new equidian());
              for (int i=0; i<25; i++)
                   Elits.add(new Elitian());
              long population = Plebs.size() + Equids..size() + Elits.size();
              System.out.println("Current Belageusia Population is "+population);
              System.out.println("Current Plebeians Population is "+Plebs.size);
              System.out.println("Current Equidians Population is "+Equids.size);
              System.out.println("Current Elitians Population is "+Elits.size);
              Random generator = new Random();
              int x = generator.nextInt(11);
              for (int j=0; j=plebs.size(); j++)
                   System.out.println(Plebs.g(j));
              long Equids_size = Equids.size();
              long Elits_size = Elits.size();
              for(int j=1; j<Plebs.size(); j++)
                   Plebian e = (Plebian) Plebs.get(j);
                   int new_ci = generator.nextInt(50);
                   if (new_ci < 25)
                        e.setCI(new_ci);
                        e.raiseDebt();
                   else
                        Plebs.rename(j);
                        Equids.add(new Equidian(e.getName().newCI));
                        j++;
              for(int j=0; j < Equids.size; j++)
                   Equidian e = (Equidian) Equids.get(j);
                   int newCI = generator.nextInt(101);
                   if(new_ci < 25)
                        Equids.remove(j);
                        Plebs.add(nwe Plebian(e.getName().new_ci));
                        Equids_size --;
                        j++;
                   else
                   if (new_ci > 75)
                        Equids.remove(j);
                        Elitian f = new Elitian(e.getName(),new_ci,e.getTaxes());
                        Elits.add(f);
                        Equids_size --;
                        j--;
                   else
                        e.setCI(new_CI);
                        e.raiseTaxes();
              for (int j=0; j<Elits.size; j++)
                   Elitian e = (Elitian) Elits.get(j);
                   int ci = e.getCI();
                   int r = generator.nextINT(50);
                   int new_ci = 51+r;
                   if(new_ci > 75)
                        e.setCI(new_ci);
                        e.raisetaxes();
                        e.raisewealth();
                   else
                        Elitians.remove(j);
                        Equidian g = new Equidian(e.getName(), new_ci);
                        g.raisetaxes();
                        Equids.add(g);
                        Elits_size --;
                        j--;
              if(deathrate != 0)
                   int multiple = 100/deathrate;
                   int count 1;
                   for (int j=0; j=Plebs.size(); j++)
                        if(count % multiple == 0)
                             Plebs.remove(j);
                             j--;
                        count++;
    class Plorg
         private final String name;
         private int CI;
         private static long nextID = 1;
         public Plorg()
              name = "Plorg" + nextID;
              nextID++;
         public Plorg(int CI)
              name = "Plorg" + nextID;
              nextID++;
              this.CI = CI;
         public Plorg (String name, int CI)
              this.name = name;
              this.CI = CI;
         public void setCI(int new_CI)
              CI = new_CI;
         public String getName()
              return name;
         public int getCI()
              return CI;
         public Plorg Plebs()
         public Plorg Equids()
         public Plorg Elits()

    Sounds a lot like a homework question to me. Still it was interesting enough to try out. I have not tried to change your code, just made one of my own. Here is my solution. I have made the Plorg class an inner class of the Belageusia. This is just so I dont have to put up two java files. You could easily split it into two though.
    import java.util.Random;
    import java.util.ArrayList;
    import java.util.Iterator;
    * @author Jonathan Knight
    public class Belageusia
        /** Random number generator - Seeded with the current time. */
        private static Random random = new Random(System.currentTimeMillis());
        /** A list of all of the Plorgs */
        private ArrayList population = new ArrayList();
        /** A list of all of the Plebians. */
        private ArrayList plebians = new ArrayList();
        /** A list of all of the Equidians. */
        private ArrayList equidians = new ArrayList();
        /** A list of all of the Elitians. */
        private ArrayList elitians = new ArrayList();
        /** A count of the Epochs that have passed */
        private int epochs = 0;
         * Main method.
         * Create a new world of Belageusia and run it for 1000 epochs.
        public static void main(String[] args)
            Belageusia world;
            world = new Belageusia();
            for (int i = 0; i < 1000; i++)
                world.epoch();
            System.out.println("The Belageusia population after 1000 epochs");
            world.printPopulation();
         * Create a new World of Belageusia and create some Plorgs to live there.
         * The world will be created with 25 Plebians, 50 Equidians and 25 Elitians.
        public Belageusia()
            for (int i = 0; i < 25; i++)
                plebians.add(Plorg.createPlebian());
            for (int i = 0; i < 50; i++)
                equidians.add(Plorg.createEquidian());
            for (int i = 0; i < 25; i++)
                elitians.add(Plorg.createElitian());
         * Print the current population to System.out
        public void printPopulation()
            int total;
            int plebianCount;
            int equidianCount;
            int elitianCount;
            plebianCount = plebians.size();
            equidianCount = equidians.size();
            elitianCount = elitians.size();
            total = plebianCount + equidianCount + elitianCount;
            System.out.println("Current Belageusia population is " + total);
            System.out.println("Current Plebian population is " + plebianCount);
            System.out.println("Current Equidian population is " + equidianCount);
            System.out.println("Current Elitian population is " + elitianCount);
         * At each interim time epoch the population of Belageusia retracts with a death rate
         * randomly selected between 0% and 10%. If a plorg survives the purge, they have an
         * opportunity to move one class higher and/or one class lower. However, remember that
         * a plorgs name is final. It never changes.
         * For Plebeians this transition is determined by randomly selecting a CI in [0, 49].
         * If this new CI is les than 25 then the plorg remains a Plebeian, with this newly assigned CI,
         * and their debt increases 3.7%. If this new CI is in [25, 49], the Plebeian ascends to a
         * Equidian, with this newly assigned CI, their debt is forgiven, but taxes of $20 are assessed.
         * For Equidians this is determined by randomly selecting a CI in [0,100].
         * If this new CI is in [25, 75] then the plorg remains a Equidian, with this newly assigned CI,
         * but their taxes are increased 6.1%.
         * If this new CI is in [0, 24] then the plorg becomes a Plebeian, with this newly assigned CI,
         * their taxes are forgiven, but they are burdened with a debt of $10.00.
         * If this new CI is in [76, 100] then the plorg becomes a Plebeian, with this newly assigned CI,
         * but their taxes are increased 6.1%. However, they are bewtowed a wealth of $30.00.
         * For Eletians this is determined by randomly selecting a CI in [51, 100].
         * If this new CI is greater than 76 then the plorg remains an Eletian, with this newly assigned CI,
         * their taxes increase 6.1% and their wealth increases 4.9%. If this new CI is in [51, 75],
         * then this plorg becomes an Equidian, with this newly assigned CI, their wealth is eliminated,
         * and their taxes are increased 6.1%.
         * At each time epoch, the population of Belageusia at a birth rate randomly selected between 0% and 10%.
         * A randomly chosen number between 0-100 determines each newly born plorg?s stature.
         * If this random number is in the range 0-24, create a new Plebeian. In the range 25-75, create a new Equidian,
         * and if in the range 76-100, create a new Elitian.
        public void epoch()
            ArrayList newPlebians = new ArrayList();
            ArrayList newEquidians = new ArrayList();
            ArrayList newEletians = new ArrayList();
            Iterator it;
            Plorg plorg;
            int deathRate;
            double deathCount;
            int birthRate;
            double birthCount;
            int population;
            int subClass;
            int newCI;
            int kill;
            epochs++;
            System.out.println("Epoch = " + epochs);
            printPopulation();
            population = plebians.size() + equidians.size() + elitians.size();
            // The death rate is random 0 to 10%
            deathRate = random.nextInt(11);
            // work out the death count. population is cast to a double to avoid rounding errors
            deathCount = (double)population * deathRate / 100;
            // round up the result. We do this as once the population falls below 10
            // we would never kill anything
            deathCount = Math.ceil(deathCount);
            // We now work out the birth rate based on the population before we kill
            // anything otherwise the population tends to go down and down
            // The birth rate is random 0 to 10%
            birthRate = random.nextInt(11);
            // work out the birth count. population is cast to a double to avoid rounding errors
            birthCount = Math.ceil((double)population * birthRate / 100);
            // As with the deathCount round up the result.
            // We do this as once the population falls too low we would never create any more
            birthCount = Math.ceil(birthCount);
            System.out.println("About to kill " + deathRate + "% which is " + deathCount + " Plorgs out of " + population);
            for(int i=0; i<deathCount; i++)
                // get a random number between 0 and 2
                kill = random.nextInt(population);
                population--;
                // kill the specified Plorg
                if( kill < plebians.size() )
                    // kill a random Plebian
                    plebians.remove( random.nextInt(plebians.size()) );
                else if( kill < plebians.size() + equidians.size() )
                    // kill a random Equidian
                    equidians.remove( random.nextInt(equidians.size()) );
                else
                    // kill a random Elitian
                    elitians.remove( random.nextInt(elitians.size()) );
            System.out.println("Transitioning Plebians");
            // Transition period for Plebians
            it = plebians.iterator();
            while ( it.hasNext() )
                plorg = (Plorg) it.next();
                // select a new CI from 0 to 49 at random
                newCI = random.nextInt(50);
                plorg.setCI(newCI);
                if( newCI < 25 )
                    // Oh dear, this one stays as a Plebian; increase its dept by 3.7%
                    plorg.setDept( plorg.getDept() * 1.037 );
                else
                    // Congratulations this one is now an Equidian
                    newEquidians.add(plorg);
                    // remove from the Plebian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    plorg.setDept(0);
                    plorg.setTaxes(20);
            System.out.println("Transitioning Equidians");
            // Transition period for Equidians
            it = equidians.iterator();
            while ( it.hasNext() )
                plorg = (Plorg) it.next();
                // select a new CI from 0 to 100 at random
                newCI = random.nextInt(101);
                plorg.setCI(newCI);
                if( newCI < 25 )
                    // Oh dear, this one becomes a Plebian
                    newPlebians.add(plorg);
                    // remove from the Equidian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    plorg.setDept( 10 );
                    plorg.setTaxes(0);
                else if( newCI < 25 )
                    // This one stays as an Equidian; increase its taxes by 6.1%
                    plorg.setTaxes( plorg.getTaxes() * 1.061 );
                else
                    // Congratulations this one is now an Eletian
                    newEletians.add(plorg);
                    // remove from the Equidian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    plorg.setWealth(30);
                    // Increase its taxes by 6.1%
                    plorg.setTaxes( plorg.getTaxes() * 1.061 );
            System.out.println("Transitioning Elitians");
            // Transition period for Eletians
            it = plebians.iterator();
            while ( it.hasNext() )
                plorg = (Plorg) it.next();
                // Always increase taxes by 6.1%
                plorg.setTaxes( plorg.getTaxes() * 1.061 );
                // select a new CI from 51 to 100 at random
                newCI = 51 + random.nextInt(50);
                plorg.setCI(newCI);
                if( newCI > 76 )
                    // This one stays as an Eletian; increase its wealth by 4.9%
                    plorg.setWealth( plorg.getWealth() * 1.049 );
                else
                    // Oh dear, this one becomes an Equidian
                    newEquidians.add(plorg);
                    // remove from the Plebian list.
                    // NOTE we must do the remove via the Iterator
                    it.remove();
                    // emove its wealth
                    plorg.setWealth(0);
            // now assign the Plorgs that are transitioning
            plebians.addAll(newPlebians);
            equidians.addAll(newEquidians);
            elitians.addAll(newEletians);
            System.out.println("Creating " + birthRate + "% new Plorgs from " + population + " which is " + birthCount);
            //create the new Plorgs
            for (int i = 0; i < birthCount; i++)
                // get a random number between 0 and 100
                subClass = random.nextInt(101);
                // create the specified Plorg
                if( subClass <= 24 )
                    plorg = Plorg.createPlebian();
                    plebians.add(plorg);
                else if( subClass >= 25 && subClass <= 75 )
                    plorg = Plorg.createEquidian();
                    equidians.add(plorg);
                else
                    plorg = Plorg.createElitian();
                    elitians.add(plorg);
        public static class Plorg
            /** Identifier used to generate unique names */
            private static int id = 0;
            /** The Plorgs name */
            private final String name;
            /** The level of wealth for this Plorg */
            private double wealth = 0;
            /** The level of dept for this Plorg */
            private double dept = 0;
            /** The level of taxes for this Plorg */
            private double taxes = 0;
            /** This Plorgs contentment index */
            private int ci = 0;
            /** Create a new Plorg with the given CI.
             * This is a private constructor. The only way for a program to
             * create new Plorgs is by calling either createPlebian(),
             * createEquidian() or createElitian().
             * @param ci
            private Plorg(int ci)
                // Generate a unique name and iincrement the ID
                this.name = "Plorg" + id++;
                // assign the CI
                this.ci = ci;
             * Create a new Plebian.
             * Plebeians have a contentment index in [0, 24].
             * Each new Plebeian is welcomed with a contentment index of 2 and burdened
             * with a debt of $10.00. Plebeians never manage to break even, so they have
             * no taxes imposed upon them. Furthermore, since they can never get out debt,
             * they cannot accumulate any wealth.
             * @return a new Plebian.
            public static Plorg createPlebian()
                Plorg plebian;
                plebian = new Plorg(2);
                plebian.setDept(10);
                return plebian;
             * Create a new Equidian
             * Equidians have a contentment index in [25, 75].
             * Each new Equidian is welcomed with a contentment index of 50 and burdened
             * with taxes of $20.00. Equidians have taxes imposed upon them. Furthermore,
             * since they do manage to break even, they have no debt. However, since they
             * only manager to break even, they do not accumulate any wealth.
             * @return a new Equidian.
            public static Plorg createEquidian()
                Plorg equidian;
                equidian = new Plorg(50);
                equidian.setTaxes(20);
                return equidian;
             * Create a new Elitian.
             * Elitians have a contentment index in [76, 100].
             * Each new Elitian is welcomed with a contentment index of 87 and burdened
             * with taxes of $20.00, but also provided with a ?silver spoon? of $30.00 in
             * accumulated wealth. Elitians manage to expand upon their wealth, so they
             * have taxes imposed upon them. Furthermore, since they are accumulating
             * wealth, they have no debt.
             * @return a new Elitian.
            public static Plorg createElitian()
                Plorg equidian;
                equidian = new Plorg(87);
                equidian.setWealth(30);
                equidian.setTaxes(20);
                return equidian;
             * Returns this Plorgs name.
            public String getName()
                return name;
             * Returns the CI of this Plorg.
            public int getCI()
                return ci;
             * Set the new Contentment index for this Plorg
             * @param ci
            public void setCI(int ci)
                this.ci = ci;
             * Returns the Dept of this Plorg
             * @return
            public double getDept()
                return dept;
             * Set the dept of this Plorg.
             * @param dept - the new dept for the Plorg.
            public void setDept(double dept)
                this.dept = dept;
             * Returns the wealth of this Plorg.
            public double getWealth()
                return wealth;
             * Sets the wealth of this Plorg.
             * @param wealth - the new wealth of this Plorg.
            public void setWealth(double wealth)
                this.wealth = wealth;
             * Returns the taxes of this Plorg.
            public double getTaxes()
                return taxes;
             * Set the taxes of this Plorg.
             * @param taxes - the new taxes for this Plorg.
            public void setTaxes(double taxes)
                this.taxes = taxes;
             * Check for equality. If the object specified is a Plorg with the same name as this
             * Plorg they are deemed to be equal.
             * @param o - The object to check
            public boolean equals(Object o)
                if ( this == o ) return true;
                if ( !(o instanceof Plorg) ) return false;
                final Plorg plorg = (Plorg) o;
                if ( name != null ? !name.equals(plorg.name) : plorg.name != null ) return false;
                return true;
             * Create a Hash Code for this Plorg
            public int hashCode()
                return (name != null ? name.hashCode() : 0);
    }

  • Please decode this error..

    i've a page that displays records from the database..i'm using mvc model...
    the records are fetched by a model and returned to a servlet and that ResultSet is added to session as an attribute.. in the jsp file i try to retrieve that ResulSet :
    ResultSet rs = (ResultSet)session.getAttribute("e_rs");
    next i display those records
    while(rs.next()) {
    i get an exception in while(rs.next()) the exception information is below....
    javax.servlet.ServletException: Operation not allowed after ResultSet closed
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:843)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:776)
         org.apache.jsp.transactions_jsp._jspService(transactions_jsp.java:167)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:334)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         com.example.web.order_history.doGet(order_history.java:29)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

    The error message is :
    Operation not allowed after ResultSet closed
    which means that the code in the JSP page is trying to access a ResultSet object which has already been closed.
    Instead of accessing the ResultSet in the JSP page I strongly encourage you to store the ResultSet in an ArrayList of a particular JavaBean object and then access that ArrayList in the JSP page.
    You will be populating the ArrayList of JavaBean objects, in the same loop that you use to iterate over the ResultSet inside the JDBC layer while accessing individual records from the result set.
    Make use of jsp:useBean tag to access the ArrayList in the JSP, and then use JSTL c:forEach tag to iterate over the resultset. JSTL 1.1 is the new way of writing JSP compared to scriptlets which make the code messy and complicated in JSPs.
    Especially if you are using MVC which strongly discourages database or business logic directly in JSP pages.

  • Java Identifer Expected Error

    Hi - I'm getting an error saying that an identifier is expected for the line d.addShare(s1);
    I don't see why I need an identifier here - I've looked in all the classes to see if its linked to them but I can't find anything wrong. Maybe it will be clear to you- I've copied and pasted all my classes here (they are not very big). Been trying to debug this for ages but to no avail.
    class Population {
    Database d = new Database();
    Random rand = new Random();
    ArrayList population = new ArrayList();
    ArrayList parents = new ArrayList();
    ArrayList contenders = new ArrayList();
    double[] reuters = {
    8.0, 9.0, 12.5, 11.5, 6, 7, 4, 2, 3, 4, 3, 5, 5.5};
    Share s1 = new Share(reuters);
    d.addShare(s1); // Error: Identifier expected
    public void initialPopulation() {
    for (int i = 0; i < 10; i++) {
    Chromosome c = new Chromosome(rand);
    c.setDatabase(d);
    population.add(c);
    System.out.println("Chromosome Weights are: " + c);
    System.out.println("Chromosome Fitness Value is: " + c.fitness(0));
    //System.out.println();
    System.out.println(population.size());
    System.out.println(population.toString());
    System.out.println();
    System.out.println(d);
    public ArrayList selectParents(int tournamentSize) {
    // Get as many chromosomes as specified by tournament size
    for (int i = 0; i < (tournamentSize); i++) {
    contenders.add(i, population.get(i));
    // Sort the sub-population in order of fitness
    // contenders.sort;
    // Return the best two
    parents.add(contenders.get(0));
    parents.add(contenders.get(1));
    //System.out.println(parents.toString());
    //System.out.println(contenders.toString());
    return parents;
    public static void main(String args[]) {
    Population p = new Population();
    p.initialPopulation();
    p.selectParents(5);
    import java.util.ArrayList;
    class Database
    { ArrayList sharedata = new ArrayList();
    public void addShare(Share s)
    { sharedata.add(s); }
    public Share getShare(int i)
    { return (Share) sharedata.get(i); }
    import java.util.ArrayList;
    import java.util.Random;
    class Chromosome
    { int[] bit = new int[12];
    Database db;
    Chromosome(Random rand)
    { for (int i = 0; i < 12; i++)
    { bit[i] = rand.nextInt(6); }
    public String toString()
    { String res = "";
    for (int i = 0; i < 12; i++)
    { res = res + bit[i] + ","; }
    return res;
    public void setDatabase(Database d)
    { db = d; }
    public double fitness(int share)
    { double prediction = 0;
    int divisor = 0;
    Share sh = db.getShare(share);
    for (int i = 0; i < 12; i++)
    { prediction = prediction + bit[i]*sh.getPrice(i);
    divisor = divisor + bit;
    if (divisor != 0)
    { prediction = prediction/divisor; }
    else
    { prediction = 0; }
    System.out.println("Prediction Value is: " + prediction);
    double actualPrice = sh.getPrice(12);
    return Math.abs(prediction - actualPrice);
    class Share
    { double[] prices = new double[13];
    Share(double[] p)
    { prices = p; }
    double getPrice(int i)
    { return prices[i]; }
    Thanks

    Thanks for that - I'm now stuck on how exactly to define the selectParent() method because I have to take out samples of size 5 (the tournament size) from the population and then order those chromosomes ( in the contenders ArrayList) in order of fitness (the lower the fitness the better). But since I'm working with ArrayLists and since I have to extract each Chromosome object from the contender Arraylist, somehow call the fitness() method on each Chromosome, and then sort in order of fitness (lowest first), I'm kind of lost with how to do this. Any ideas on this? What's the simplest way of doing it? Thanks

Maybe you are looking for

  • Error saving Project 2010 files to network drive - doesn't see network drive

    ANSWERED (11 April 2014): So it seems the resolution to this is to simply create a new share with a different name. I used the existing folder (to retain NTFS permissions) and just select to Add a new Share (applying the same Share permissions as the

  • Cascade delete in database

    Hi all, i've tow entites, TCompte and THisto define as : public class TCompte { public class THisto { @ManyToOne(optional = false) TCompte theCompte; }i've persist many instance of each. when i try to remove an instance of TCompte i got an exception

  • Parsing a xml file

    i need a code for this... write a class for "myxmlparser" to parse "*.xml" fileto "*.dtd" file. sundar

  • Zen micro photo batt

    I have heard that the zen micro and the zen micro photo have the same battery size, but the photos has a higher capacity. Would it be possible to buy a photo battery and put it in say a zen micro 5gb?

  • IBooks Author Crashing

    I have almost completed an iBook using iBooks Author.  However in the final stages it keeps crashing.  It is quite a big file - around 1.5 GB and full of multimedia.  Any ideas on how to overcome this issue.  Many thanks.