ArrayList

Hi
I have written a simple ArrayList program
import java.util.*;
class ArrayDemo {
     public static void main(String[] args) {
          ArrayList a = new ArrayList();
          a.add("1");
          a.add("2");
          System.out.println(a);
when i compile this code it is giving an error
Note: F:\rajesh\ArrayDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Tool completed successfully
I havn't seen this this error before as I am new to java programming can Anyone help me to know why i am getting this error. I am using JDK1.5 and running the programming on Textpad.

this is laxman
When we write a program by using interfaces we have to specify its Class. It means which kind of data is u are using to do the task.
Ex:
ArrayList al = new ArrayList(); u have written
the correct form is:
ArrayList<Object> al = new ArrayList<Object>;
it avoid the error which was generated by ur program.
<Integer>
<String>
<Double> etc
incase of your program u have to write: if you are using Strings
ArrayList<String> al = new ArrayList<String>;
if you are using integers
ArrayList<Integer> al = new ArrayList<Integer>

Similar Messages

  • ArrayList e .RangeCheck(int)line 546

    Hi guys I am working on this project
    in few word
    I have to draw different shape on a panel
    moreover when two similar shapes collide ( 2 circles ) they make a bigger circle
    when st change direction
    almost everything works
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.Iterator;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel implements ActionListener {
         private static final long serialVersionUID = 1L;
         public static ArrayList <Shape>shapes;
         private javax.swing.Timer animationTmr;
         int speed;
         PlaySound audioClip = new PlaySound();
         private float heigth;
         private float width;
         private int shape1;
         private int shape2;
         public ShapePanel() {
              shapes = new ArrayList<Shape>();
              animationTmr = new javax.swing.Timer(80, this); //interval, ActionListener
              animationTmr.start();
         public ArrayList<Shape> getShapes()
              return shapes;
         public void addSquare(int x, int y,int w,int h, int shapeType) {
              shapes.add(new Square(this,x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void addCircle(int x, int y,int w,int h, int shapeType) {
              shapes.add(new Circle(this, x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void addRectangle(int x, int y,int w,int h,  int shapeType) {
              shapes.add(new Rectangle(this, x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void addStar(int x, int y,int w,int h, int shapeType) {
              shapes.add(new Star(this, x, y,width, heigth, shapeType));
              repaint();
              System.out.println(shapes.size());
         public void paintComponent(Graphics g) { //called Whenever panel needs
              super.paintComponent(g); //re-displaying:
              Iterator<Shape> it = shapes.iterator(); //Iterate through Balls calling
              g.setColor(Menu.getColor());
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
              while (it.hasNext()) { //each one's paint method
                   it.next().paint(g);
         public void actionPerformed(ActionEvent ev) {      
              //On timer tick,
              Iterator<Shape> it = shapes.iterator(); //Iterate through Balls calling
              while (it.hasNext()) { //each one's updatePos() method
                   it.next().updatePos();
              checkTypeCollision();
              handleCollision();
              repaint();
        private void checkTypeCollision()
              //we iterate through all the balls, checking for collision
              for(int i=0;i<shapes.size();i++)
                   for(int j=0;j<shapes.size();j++)
                             if(i!=j)
                                  if(collide(shapes.get(i), shapes.get(j)))
                                            shape1=shapes.get(i).shapeType;
                                            shape2=shapes.get(j).shapeType;
                                             if(shape1==shape2)
                                             /*     int     newX = (int) ((shapes.get(i).getCenterX() + (shapes.get(j).getCenterX()/2))/2);
                                                  int newY = (int) ((shapes.get(i).getCenterY() + (shapes.get(j).getCenterY() /2))/2);
                                                 float newWidth =   shapes.get(i).getWidth()+(shapes.get(j).getWidth()/2);
                                                 float newHeigth = shapes.get(i).getHeigth()+(shapes.get(j).getHeigth()/2);
                                                 int newShapeType = shapes.get(i).shapeType;
                                                       if(shapes.get(i).getShapeType()==1)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                            System.out.println("SIZE IS==="+     shapes.size());
                                                            System.out.println("newx====="+newX);
                                                            System.out.println("newy====="+newY);
                                                            System.out.println("newWidth====="+newWidth);
                                                            System.out.println("newx====="+newHeigth);
                                             //               shapes.add(new Rectangle(this,newX,newY,530,530,newShapeType));
                                                            System.out.println("SIZE IS==="+     shapes.size());
                                                       //     repaint();
                                                       if(shapes.get(i).getShapeType()==2)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                  //          shapes.add(new Circle(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       //     repaint();
                                                       if(shapes.get(i).getShapeType()==3)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                            shapes.add(new Square(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       if(shapes.get(i).getShapeType()==3)
                                                            shapes.remove(j); //remove shape element at j
                                                            shapes.remove(i); //remove shape element at j
                                                            //shapes.add(new Star(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       //     repaint();
         private void handleCollision()
              //we iterate through all the balls, checking for collision
              for(int i=0;i<shapes.size();i++)
                   for(int j=0;j<shapes.size();j++)
                             if(i!=j)
                                  if(collide(shapes.get(i), shapes.get(j)))
                                        shapes.get(i).hit(shapes.get(j));
                                       shapes.get(j).hit(shapes.get(i));                                   
         boolean collide(Shape b1, Shape b2)
              double wx=b1.getCenterX()-b2.getCenterX();
              double wy=b1.getCenterY()-b2.getCenterY();
              //we calculate the distance between the centers two
              //colliding balls (theorem of Pythagoras)
              double distance=Math.sqrt(wx*wx+wy*wy);
              if(distance<b1.shapeSize)     
                   audioClip.playRectangle();
                   return true;          
                   else return false;     
         public static int vectorSize()
              return shapes.size();
    }the drawing stops and
    i have this error after a while
    arrayList<e>.RangeCheck(int)line 546
    moreover it doesn t draw a bigger shape as i want with the line
    shapes.add(new Circle(this,newX,newY,newWidth,newHeigth,newShapeType));
                                                       help please the deadline is Tomorrow;

    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
         at java.util.ArrayList.RangeCheck(ArrayList.java:546)
         at java.util.ArrayList.get(ArrayList.java:321)
         at ShapePanel.checkTypeCollision(ShapePanel.java:156)
         at ShapePanel.actionPerformed(ShapePanel.java:77)
         at javax.swing.Timer.fireActionPerformed(Timer.java:271)
         at javax.swing.Timer$DoPostEvent.run(Timer.java:201)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    it doesn t compile because is part of a bigger project

  • Check for null and empty - Arraylist

    Hello all,
    Can anyone tell me the best procedure to check for null and empty for an arraylist in a jsp using JSTL. I'm trying something like this;
    <c:if test="${!empty sampleList}">
    </c:if>
    Help is greatly appreciated.
    Thanks,
    Greeshma...

    A null check might not be you best option.  If your requirement is you must have both the date and time component supplied in order to populate EventDate, then I would use a Script Functoid that takes data and time as parameters.
    In the C# method, first check if either is an empty string, if so return an empty string.
    If not, TryParse the data, if successful, return a valid data string for EventDate.  If not, error or return empty string, whichever satsifies the requirement.

  • Problem getting arraylist values from request

    Hi All,
    I am trying to display the results of a search request.
    In the jsp page when I add a scriplet and display the code I get the values else it returns empty as true.Any help is appreciated.
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
         <%@ include file="/includes/header.jsp"%>
         <title>Research Results</title>
    </head>
    <body>
    <div class="ui-widget  ui-widget-content">
        <%  
        ArrayList<Research> research = (ArrayList<Research>) request.getAttribute("ResearchResults");
         Iterator iterator = research.iterator();
              while(iterator.hasNext()){
              Research r = (Research) iterator.next();
              out.println("Result Here"+r.getRequesterID());
              out.println("Result Here"+r.getStatus());
        %> 
         <form>
         <c:choose>
         <c:when test='${not empty param.ResearchResults}'>
         <table cellspacing="0" cellpadding="0" id="research" class="sortable">
         <h2>RESEARCH REQUESTS</h2>
                   <tr>
                   <th><a href="#">RESEARCH ID</a></th>
                   <th><a href="#">REQUESTOR NAME</a></th>
                   <th><a href="#">DUE DATE</a></th>
                   <th><a href="#">REQUEST DATE</a></th>
                   <th><a href="#">CLIENT</a></th>
                   <th><a href="#">STATUS</a></th>
                   <th><a href="#">PRIORITY</a></th>
                   </tr>
              <c:forEach var="row" items="${param.ResearchResults}">
                        <tr title="">
                             <td id="researchID">${row.RESEARCH_ID}</td>
                             <td>${row.REQUESTER_FNAME}  ${row.REQUESTER_LNAME}</td>
                             <td><fmt:formatDate pattern="MM/dd/yyyy" value="${row.DUE_DATE}"/></td>
                             <td><fmt:formatDate pattern="MM/dd/yyyy" value="${row.CREATED_DATE}"/></td>
                             <td>${row.CLIENT}</td>
                             <td>
                             <c:choose>
                               <c:when test="${row.STATUS=='10'}">New Request</c:when>
                               <c:when test="${row.STATUS=='20'}">In Progress</c:when>
                               <c:when test="${row.STATUS=='30'}">Completed</c:when>
                              </c:choose>
                             </td>
                             <td>
                             <c:choose>
                               <c:when test="${row.PRIORITY=='3'}">Medium</c:when>
                               <c:when test="${row.PRIORITY=='2'}">High</c:when>
                               <c:when test="${row.PRIORITY=='1'}">Urgent</c:when>
                              </c:choose>
                             </td>
                             </tr>
              </c:forEach>
         </table>
         </c:when>
         <c:otherwise>
         <div class="ui-state-highlight ui-corner-all">
                   <p><b>No results Found. Please try again with a different search criteria!</b> </p>
              </div>
         </c:otherwise>
         </c:choose>
         </form>
              <%@ include file="/includes/footer.jsp"%>
         </div>
         </body>
    </html>

    What is ResearchResults?
    Is it a request parameter or is it a request attribute?
    Parameters and attributes are two different things.
    Request parameters: the values submitted from the form. Always String.
    Request attributes: objects stored into scope by your code.
    They are also accessed slightly differently in EL
    java syntax == EL syntax
    request.getParameter("myparameter") == ${param.myparameter}
    request.getAttribute("myAttribute") == ${requestScope.myAttribute}
    You are referencing the attribute in your scriptlet code, but the parameter in your JSTL/EL code.
    Which should it be?
    cheers,
    evnafets

  • How to input data into an arraylist from a text file?

    I am trying to take data from a text file and put that data into an arraylist. First here is the text file:
    [item1, 10, 125.0, item2, 10, 12.0, item3, 20, 158.0]
    3
    4530.0
    [item5, 65, 555.5, item4, 29, 689.0]
    2
    56088.5
    [item7, 84, 34.5, item6, 103, 0.5, item8, 85, 1.36]
    3
    3065.1The text between the [ ] is the output from my arraylists. I have three arraylists. The first [ ] belongs to arraylist A, the second to arraylist B, and the third to arraylist C. The format of the arraylists is this:
    <item name>,<# in stock>,<value of one item>
    The first number below the arraylists in the text file represents the number of items in the list. The second number below the arraylists represents the total value of the items in the arraylists.
    Here is the class file I have (yes, it does everything):
    import java.io.*;
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Inventory extends Object
         public int toAdd = 0;
         private boolean done = false;               //Are we done yet?
         public String strItemName;                    //The name of the item type.
         public int intNumInStock;                    //The number in stock of that type.      
         public double dblValueOfOneItem;          //The value of one item.
        public String strNumberInStock;               
        public double dblTotalValueA;               //The total value of warehouse A.
        public double dblTotalValueB;               //The total value of warehouse B.
        public double dblTotalValueC;               //The total value of warehouse C.
        public int intWarehouseAItemCount;          //Counter for items in warehouse A.
        public int intWarehouseBItemCount;          //Counter for items in warehouse B.
        public int intWarehouseCItemCount;          //Counter for items in warehouse C.
         ArrayList warehouseAList = new ArrayList();     //Create the Warehouse A ArrayList.                                   
         ArrayList warehouseBList = new ArrayList(); //Create the Warehouse B arrayList.
         ArrayList warehouseCList = new ArrayList(); //Create the Warehouse C arrayList.
         /** Construct a new Inventory object. */
         public Inventory()
              super();
         /**Add items to the Warehouse A ArrayList.*/
         private void createWareHouseA()
              System.out.println("!" + toAdd + " item types will be added to warehouse A.");
              //Cast
              String strNumInStock = Integer.toString(intNumInStock);
              String strValueOfOneItem = Double.toString(dblValueOfOneItem);
              this.strNumberInStock = strNumInStock;
              System.out.println("!Initial size of warehouseAList :  " +
                                                                warehouseAList.size());
              //Add items to the array List
              warehouseAList.add(this.strItemName);
              warehouseAList.add(this.strNumberInStock);
              warehouseAList.add(this.dblValueOfOneItem);
              System.out.println("!size of arrayList after additions " + warehouseAList.size());
         /**Add items to the Warehouse B ArrayList.*/
         private void createWareHouseB()
              System.out.println("!" + toAdd + " item types will be added to warehouse B.");
              //Cast
              String strNumInStock = Integer.toString(intNumInStock);
              String strValueOfOneItem = Double.toString(dblValueOfOneItem);
              this.strNumberInStock = strNumInStock;
              System.out.println("!Initial size of warehouseBList :  " +
                                                                warehouseBList.size());
              //Add items to the array List
              warehouseBList.add(this.strItemName);
              warehouseBList.add(this.strNumberInStock);
              warehouseBList.add(this.dblValueOfOneItem);
              System.out.println("!size of arrayList after additions " + warehouseBList.size());
         /**Add items to the Warehouse C ArrayList.*/
         private void createWareHouseC()
              System.out.println("!" + toAdd + " item types will be added to warehouse C.");
              //Cast
              String strNumInStock = Integer.toString(intNumInStock);
              String strValueOfOneItem = Double.toString(dblValueOfOneItem);
              this.strNumberInStock = strNumInStock;
              System.out.println("!Initial size of warehouseCList :  " +
                                                                warehouseCList.size());
              //Add items to the array List
              warehouseCList.add(this.strItemName);
              warehouseCList.add(this.strNumberInStock);
              warehouseCList.add(this.dblValueOfOneItem);
              System.out.println("!size of arrayList after additions " + warehouseCList.size());
         /**Interpret the commands entered by the user.*/
         public void cmdInterpreter()
              this.displayHelp();
              Scanner cin = new Scanner(System.in);
              while (!this.done)
                   System.out.print(">");
                   //"line" equals the next line of input.
                   String line = cin.nextLine();
                   this.executeCmd(line);
         /**Execute one line entered by the user.
          * @param cmdLN; The command entered by the user to execute. */
          private void executeCmd(String cmdLN)
               Scanner line = new Scanner(cmdLN);
               if (line.hasNext())
                    String cmd = line.next();
                    //What to do when users enter the various commands below.
                    if (cmd.equals("help"))
                         this.displayHelp();
                    else if (cmd.equals("Q!"))
                         this.done = true;
                    else if (cmd.equals("F") && line.hasNext())
                         this.inputFromFile(line.next());
                    else if (cmd.equals("K") && line.hasNext())
                         int numItemsToAdd = Integer.valueOf( line.next() ).intValue();
                         this.toAdd = numItemsToAdd;
                         this.inputFromKeyboard(numItemsToAdd);
          /**What to do if input comes from a file.
           *     @param inputFile; The name of the input file to process.*/
          private void inputFromFile(String inputFile)
               Scanner cin = new Scanner(System.in);
               System.out.println("!Using input file " + inputFile + ".");
               System.out.print("!Enter the name of the output file: ");
               String outputFile = cin.next();
               System.out.println("!Using output file " + outputFile + ".");
              try
                   BufferedReader in = new BufferedReader(new FileReader(inputFile));
                   //Scanner in = new Scanner(new File(inputFile));
                   //Initialize the String variables.
                   String line1 = null;
                   String line2 = null;
                   String line3 = null;
                   String line4 = null;
                   String line5 = null;
                   String line6 = null;
                   String line7 = null;
                   String line8 = null;
                   String line9 = null;
                   System.out.println(in.equals(",") + " see?");
                   //System.out.println((char)(char)in.read() + " experiment");
                   /**This loop assigns values to the string variables based on the
                    * values on each line in the input file. */
                   while(in.readLine() != null)
                        line1 = in.readLine();
                        line2 = in.readLine();
                        line3 = in.readLine();
                        line4 = in.readLine();
                        line5 = in.readLine();
                        line6 = in.readLine();
                        line7 = in.readLine();
                        line8 = in.readLine();
                        line9 = in.readLine();
                   //Print the contents of each line in the input file.
                   System.out.println("!value of line 1: " + line1);
                   System.out.println("!value of line 2: " + line2);
                   System.out.println("!value of line 3: " + line3);
                   System.out.println("!value of line 4: " + line4);
                   System.out.println("!value of line 5: " + line5);
                   System.out.println("!value of line 6: " + line6);
                   System.out.println("!value of line 7: " + line7);
                   System.out.println("!value of line 8: " + line8);
                   System.out.println("!value of line 9: " + line9);
                /**Add items to the warehouses.*/
                   warehouseAList.add(line1);
                   warehouseBList.add(line4);
                   warehouseCList.add(line7);
                /**Add the item count and total value for warehouse A.*/
                   int intLine2 = Integer.valueOf(line2).intValue();
                   this.intWarehouseAItemCount = intLine2;
                   double dblLine3 = Double.valueOf(line3).doubleValue();
                   this.dblTotalValueA = dblLine3;
                /**Add the item count and total value for warehouse B.*/
                   int intLine5 = Integer.valueOf(line5).intValue();
                   this.intWarehouseBItemCount = intLine5;
                   double dblLine6 = Double.valueOf(line6).doubleValue();
                   this.dblTotalValueB = dblLine6;
                /**Add the item count and total value for warehouse C.*/
                  int intLine8 = Integer.valueOf(line8).intValue();
                  this.intWarehouseCItemCount = intLine8;
                  double dblLine9 = Double.valueOf(line9).doubleValue();
                  this.dblTotalValueC = dblLine9;
                /**Ask the user how many items to add or delete from inventory.*/
                  System.out.print("Enter the number to add to inventory for " +
                                                               warehouseAList.get(0) + ":");
                  String toAddOrDel = cin.next();
                /**Print the contents of all the warehouses. */
                   System.out.println(" ");
                   //Print the contents of warehouse A.
                   System.out.println("!--------------------------------");
                   System.out.println("!----------Warehouse A:----------");
                   System.out.println("!--------------------------------");
                   //Print the item list for warehouse A.
                   System.out.println(warehouseAList);
                   //Print the total amount of items in warehouse A.
                   System.out.println("Total items: " + this.intWarehouseAItemCount);
                   //Print the total value of the items in warehouse A.
                   System.out.println("Total value: " + this.dblTotalValueA);
                   System.out.println("!--------------------------------");
                   System.out.println("!----------Warehouse B:----------");
                   System.out.println("!--------------------------------");
                   //Print the item list for warehouse B.
                   System.out.println("!warehouseB: " + warehouseBList);
                   //Print the total amount of items in warehouse B.
                   System.out.println("Total items: " + this.intWarehouseBItemCount);
                   //Print the total value of the items in warehouse B.
                   System.out.println("Total value: " + this.dblTotalValueB);
                   System.out.println("!--------------------------------");
                   System.out.println("!----------Warehouse C:----------");
                   System.out.println("!--------------------------------");
                   //Print the item list for warehouse C.
                   System.out.println("!warehouseC: " + warehouseCList);
                   //Print the total amount of items in warehouse C.
                   System.out.println("Total items: " + this.intWarehouseCItemCount);
                   //Print the total value of the items in warehouse C.
                   System.out.println("Total value: " + this.dblTotalValueC);
                   in.close();
              catch (FileNotFoundException e)
                   System.out.println("!Error: Unable to open file for reading.");
              catch (EOFException e)
                   System.out.println("!Error: EOF encountered, file may be corrupted.");
              catch (IOException e)
                   System.out.println("!Error: Cannot read from file.");
          /**What to do if input comes from the keyboard.
           *     @param numItems; The total number of items that will be added to the
           *                      Warehouse(s). */
          public void inputFromKeyboard(int numItems)
               System.out.println("!You will be adding " + numItems + " items to " +
                                             "inventory from the keyboard. ");
               this.toAdd = numItems;
               Scanner cin = new Scanner(System.in);
               //Prompt user for name of output file.
               System.out.print("!Enter the name of the output file: ");
               String outputFile = cin.next();
               /**This loop asks the user for information about the item(s) and inputs
                 *them into the appropriate array.*/
               int count = 0;
               while (numItems > count)
                    //Item name.
                    System.out.print("!Item name: ");
                    String addItemName = cin.next();
                    //Number in stock.
                    System.out.print("!Number in stock: ");
                    String addNumInStock = cin.next();
                    //Initial warehouse.
                    System.out.print("!Initial warehouse(A,B,C): ");
                    String addInitWarehouse = cin.next();
                    //Value of one item.
                    System.out.print("!Value of one item: ");
                    String addValueOfOneItem = cin.next();
                    //Add or delete from inventory
                    System.out.print("!Enter amount to add or delete from inventory: ");
                    String strAddOrDelete = cin.next();
                    System.out.println("!Amount to add or delete: " + strAddOrDelete);
                    //Cast
                    int intAddNumInStock = Integer.valueOf(addNumInStock).intValue();
                    double doubleAddValueOfOneItem = Double.valueOf(addValueOfOneItem).doubleValue();
                    int intAddOrDelete = Integer.valueOf(strAddOrDelete).intValue();
                    /**Add intAddNumInStock with intAddOrDelete to determine the amount
                     * to add or delete from inventory (If a user wishes to remove items
                     * from inventory simply add negative values). */
                    intAddNumInStock = intAddNumInStock + intAddOrDelete;
                    System.out.println("!Inventory after modifications: " + strAddOrDelete);
                    this.strItemName = addItemName;
                    this.intNumInStock = intAddNumInStock;
                    this.dblValueOfOneItem = doubleAddValueOfOneItem;
                    //Put items into warehouse A if appropriate.
                    if (intAddNumInStock < 25)
                        //Increment the warehouse A item count.
                        this.intWarehouseAItemCount = this.intWarehouseAItemCount + 1;
                        //Calculate the total value of warehouse A.
                        this.dblTotalValueA = this.dblTotalValueA + intAddNumInStock * doubleAddValueOfOneItem;
                        //Create the warehouse A array list.
                        this.createWareHouseA();
                    //Put items into warehouse B if appropriate.
                    if (intAddNumInStock >= 25)
                        if (intAddNumInStock < 75)
                             //Increment the warehouse B item count.
                             this.intWarehouseBItemCount = this.intWarehouseBItemCount + 1;
                             //Calculate the total value of warehouse B.
                             this.dblTotalValueB = this.dblTotalValueB + intAddNumInStock * doubleAddValueOfOneItem;
                             //Create the warehouse B array list.
                             this.createWareHouseB();
                    //Put items into warehouse C if appropriate.
                    if (intAddNumInStock >= 75)
                        //Increment the warehouse C item count.
                        this.intWarehouseCItemCount = this.intWarehouseCItemCount + 1;
                        //Calculate the total value of warehouse C.
                        this.dblTotalValueC = this.dblTotalValueC + intAddNumInStock * doubleAddValueOfOneItem;
                        //Create the warehouse C array list.
                        this.createWareHouseC();
                     //display helpful information.      
                    System.out.println("!--------------------------------");
                    System.out.println("!" + addItemName + " is the item name.");
                    System.out.println("!" + addNumInStock + " is the number in stock.");
                    System.out.println("!" + addInitWarehouse + " is the initial warehouse.");
                    System.out.println("!" + addValueOfOneItem + " is the value of one item.");
                    System.out.println("!--------------------------------------------------");
                   //Increment the counters.
                    count++;
               /**Create and write to the output file. */
               try
                     //Use the output file specified by the user.
                    PrintWriter out = new PrintWriter(outputFile);
                 /**Write warehouse A details.*/
                      //Blank the first line.
                      out.println(" ");
                    //Write the array list for warehouse A.
                    out.println(warehouseAList);
                    //Write the amount of items in warehouse A.
                    out.println(intWarehouseAItemCount);
                    //Write the total value for warehouse A.
                    out.println(dblTotalValueA);
                 /**Write warehosue B details.*/
                   //Write the array list for warehouse B.
                    out.println(warehouseBList);
                    //Write the amount of items in warehouse B.
                    out.println(intWarehouseBItemCount);
                    //Write the total value for warehouse B.
                    out.println(dblTotalValueB);
                 /**Write warehouse C details.*/
                      //Write the array list for warehouse C.
                    out.println(warehouseCList);
                    //Write the amount of items in warehouse C.
                    out.println(intWarehouseCItemCount);
                    //Write the total value for warehouse C.
                    out.println(dblTotalValueC);
                    //Close the output file.
                    out.close();     
                catch (FileNotFoundException e)
                   System.out.println("Error: Unable to open file for reading.");
               catch (IOException e)
                   System.out.println("Error: Cannot read from file.");
               /**View the contents and the value of each warehouse.*/
               System.out.println("!---------------Inventory Summary------------------");
               System.out.println("!--------------------------------------------------");
               System.out.println("!--------------------LEGEND:-----------------------");
               System.out.println("!<item type>, <amount in stock>,<value of one item>");
               System.out.println("!--------------------------------------------------");
               System.out.println("!------------------Warehouse A:--------------------");
               System.out.println("!--------------------------------------------------");
               //Display Items in warehouse A.
               System.out.println(warehouseAList);
               //Total items in warehouse A.
               System.out.println("Total items: " + intWarehouseAItemCount);
               //Display total value of warehouse A.
               System.out.println("Total value: " + "$" + dblTotalValueA);
               System.out.println("!--------------------------------------------------");
               System.out.println("!------------------Warehouse B:--------------------");
               System.out.println("!--------------------------------------------------");
               //Display Items in warehouse B.
               System.out.println(warehouseBList);
               //Total items in warehouse B.
               System.out.println("Total items: " + intWarehouseBItemCount);
               //Display total value of warehouse B.
               System.out.println("Total value: " + "$" + dblTotalValueB);
               System.out.println("!--------------------------------------------------");
               System.out.println("!------------------Warehouse C:--------------------");
               System.out.println("!--------------------------------------------------");
               //Display Items in warehouse C.
               System.out.println(warehouseCList);
               //Total items in warehouse C.
               System.out.println("Total items: " + intWarehouseCItemCount);
               //Display total value of warehouse C.
               System.out.println("Total value: " + "$" + dblTotalValueC);
         /**Display a help message.*/
         private void displayHelp()
              System.out.println("!--------------------------------");
              System.out.println("! General Help:");
              System.out.println("!--------------------------------");
              System.out.println("! ");
              System.out.println("!'help' display this help message.");
              System.out.println("!'Q!' quit this program.");
              System.out.println("!--------------------------------");
              System.out.println("! Input File Specific Commands:");
              System.out.println("!--------------------------------");
              System.out.println("! ");
              System.out.println("!'F' <name> type F followed by the name of the " +
                                       "file to be used for input.");
              System.out.println("!---------------------------------------");
              System.out.println("! Input From Keyboard Specific Commands:");
              System.out.println("!---------------------------------------");
              System.out.println("! ");
              System.out.println("!'K' <number> type K followed by the number of " +
                                        "items that will be added. ");
              System.out.println("! ");
    }Program file:
    public class InventoryProg
         public static void main(String[] args)
              //Create a new Inventory object.
              Inventory test = new Inventory();
              //Execute the command interpreter.
              test.cmdInterpreter();
    }Right now I am stuck on this and I cannot progress any further until I figure out how to input the data in the text file back into a arraylist.
    Thanks in advance.

    Thanks but I figured it out. Heres a sample of the code i used to solve my problem:
    try
                           //Warehouse A BufferedReader.
                   BufferedReader inA = new BufferedReader(new FileReader(inputFileWarehouseA));
                   //Warehouse B BufferedReader.
                   BufferedReader inB = new BufferedReader(new FileReader(inputFileWarehouseB));
                   //Warehouse C BufferedReader.
                   BufferedReader inC = new BufferedReader(new FileReader(inputFileWarehouseC));
                   //Warehouse details BufferedReader.
                   BufferedReader inDetails = new BufferedReader(new FileReader(inputFileDetails));
                   //Will hold values in warehouse arraylists.
                   String lineA = null;
                   String lineB = null;
                   String lineC = null;
                   //Will hold the details of each warehouse.
                   String line1 = null;
                   String line2 = null;
                   String line3 = null;
                   String line4 = null;
                   String line5 = null;
                   String line6 = null;
                   //Get the item count and total value for each warehouse.
                   while(inDetails.readLine() != null)
                        line1 = inDetails.readLine();
                        line2 = inDetails.readLine();
                        line3 = inDetails.readLine();
                        line4 = inDetails.readLine();
                        line5 = inDetails.readLine();
                        line6 = inDetails.readLine();
               /**Assign the item count and total value to warehouse A.*/
                  //Cast.
                   int intLine1 = Integer.valueOf(line1).intValue();
                   double dblLine2 = Double.valueOf(line2).doubleValue();
                   //Assign the values.
                   this.intWarehouseAItemCount = intLine1;
                   this.dblTotalValueA = dblLine2;
                /**Assign the item count and total value to warehouse B.*/
                     //Cast.
                   int intLine3 = Integer.valueOf(line3).intValue();
                   double dblLine4 = Double.valueOf(line4).doubleValue();
                     //Assign the values.
                   this.intWarehouseBItemCount = intLine3;
                   this.dblTotalValueB = dblLine4;
                /**Assign the item count and total value to warehouse C.*/
                     //Cast.
                     int intLine5 = Integer.valueOf(line5).intValue();
                   double dblLine6 = Double.valueOf(line6).doubleValue();
                   //Assign the values.
                   this.intWarehouseCItemCount = intLine5;
                   this.dblTotalValueC = dblLine6;
                /**Put the items back into the warehouses arraylists. */
                   //Add items to warehouse A.
                   while((lineA = inA.readLine()) != null)
                        warehouseAList.add(lineA);
                   //Add items to warehouse B.
                   while((lineB = inB.readLine()) != null)
                        warehouseBList.add(lineB);
                   //Add items to warehouse C.
                   while((lineC = inC.readLine()) != null)
                        warehouseCList.add(lineC);
                   }(this isn't the whole try statement its pretty long)

  • How can I move an ArrayList from one method to another?

    As the subject reveals, I want to know how I move an ArrayList. In one method, I fill my ArrayList with objects, and in the next I want to pick an arbitrary object out of the ArrayList.
    How do I make this work??

    You pass the same array list to both the method. Both method are getting the same thing.
    void main(){
    //create array list here
    ArrayList aList = new ArrayList();
    //pass it to a method to fill items
    fillArrayList(aList);
    //pass the same arraylist to another method
    printArrayList(aList);
    void fillArrayList(ArrayList list){
      list.add("A");
    void printArrayList(ArrayList list){
    //The array list will contain A added by the previos method
    System.out.println(list);
    FeedFeeds : http://www.feedfeeds.com                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Create a JTable based on an ArrayList containing instances of a class.

    I have a class, IncomeBudgetItem, instances of which are contained in an ArrayList. I would like to create a JTable, based on this ArrayList. One variable is a string, while others are type double. Not all variables are to appear in the JTable.
    The internal logic of my program is already working. And my GUI is largely constructed. I'm just not sure how to make them talk to each other. The actually creation of the JTable is my biggest problem right now.

    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class TableDemo extends JPanel {
         private boolean DEBUG = false;
         public TableDemo() {
              super(new GridLayout(1, 0));
              ArrayList<MyObject> list = new ArrayList<MyObject>();
              list.add(new MyObject("Kathy", "Smith", "Snowboarding", new Integer(5),
                        new Boolean(false)));
              list.add(new MyObject("John", "Doe", "Rowing", new Integer(3),
                        new Boolean(true)));
              list.add(new MyObject("Sue", "Black", "Knitting", new Integer(2),
                        new Boolean(false)));
              list.add(new MyObject("Jane", "White", "Speed reading",
                        new Integer(20), new Boolean(true)));
              JTable table = new JTable(new MyTableModel(list));
              table.setPreferredScrollableViewportSize(new Dimension(500, 70));
              table.setFillsViewportHeight(true);
              // Create the scroll pane and add the table to it.
              JScrollPane scrollPane = new JScrollPane(table);
              // Add the scroll pane to this panel.
              add(scrollPane);
         class MyObject {
              String firstName;
              String lastName;
              String sport;
              int years;
              boolean isVeg;
              MyObject(String firstName, String lastName, String sport, int years,
                        boolean isVeg) {
                   this.firstName = firstName;
                   this.lastName = lastName;
                   this.sport = sport;
                   this.years = years;
                   this.isVeg = isVeg;
         class MyTableModel extends AbstractTableModel {
              private String[] columnNames = { "First Name", "Last Name", "Sport",
                        "# of Years", "Vegetarian" };
              ArrayList<MyObject> list = null;
              MyTableModel(ArrayList<MyObject> list) {
                   this.list = list;
              public int getColumnCount() {
                   return columnNames.length;
              public int getRowCount() {
                   return list.size();
              public String getColumnName(int col) {
                   return columnNames[col];
              public Object getValueAt(int row, int col) {
                   MyObject object = list.get(row);
                   switch (col) {
                   case 0:
                        return object.firstName;
                   case 1:
                        return object.lastName;
                   case 2:
                        return object.sport;
                   case 3:
                        return object.years;
                   case 4:
                        return object.isVeg;
                   default:
                        return "unknown";
              public Class getColumnClass(int c) {
                   return getValueAt(0, c).getClass();
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("TableDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up the content pane.
              TableDemo newContentPane = new TableDemo();
              newContentPane.setOpaque(true); // content panes must be opaque
              frame.setContentPane(newContentPane);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    }

  • Help :add multiple rows from Resultset to ArrayList ?

    My query returns one column and multiple rows. In Java code , I am trying to get this data in array or arraylist through ResultSet
    ex:
    item_num
    p001
    p002
    p003
    when I print, it only gets the item in the first row.
    ArrayList myArrayList = new ArrayList();
    resultset = preparedstatement.executeQuery();
    if (resultset.next())
    myArrayList.add(new String(resultset.getString("item_num")));
    Print:
    for (int j = 0 ; j < myArrayList.size() ; j++ )
    System.out.println((String)myArrayList.get(j)); --this prints only the first item.
    can someone assist ?

    changing if to while fixed it.

  • How to modify numbers in a arraylist?

    Say I have an arraylist with these values:
    [item1, 65, 555.5]item1 represents the name of an item type, 65 represents the number in stock, and 555.5 represents the value of one item.
    Now say I want to add 10 item1's to the number in stock. So I want to change the 65 in the array list to a 75. How could I do this?
    Thanks

    This would be a lot easier if you created a class to encapsulate those three data members, then created a list of those objects. The class could have three variables, name, stock, and value. Then it's easy to write a method to add or subract to the stock of a particular item, and you don't have to worry about modifying the wrong element in the list, casting elements to the right type (String, int, float, etc).
    public class Item {
        private String name;
        private int stock;
        private float value;
    }

  • ArrayList prob

    Hi,
    Im trying to create a program which deals with stats for a football team. I have a class Player containing games played and goals scored which externds from a Class Person which contains details such as Name, DoB ,height etc.
    I am trying to store my players in an Arraylist so i can use Comparable to change the order of the list e,g( by name, by games played, by goals scored.)
    However, using the BlueJ environment i get i get a compiler error : Using unsafe or unchecked operations on the ArrayList.add line, and a Null exception when running the following code:
    import java.util.*;
    public class Club
        private String clubName;
        private String name;
        private String surname;
        private int ageInYears;
        private int heightInCm;
        private int weightInKg;
        private int goals;
        private int games;
        private ArrayList playerList;
        public Club(String clubName)   
         this.clubName= clubName;
         ArrayList<Player> playerList =  new ArrayList<Player>();
        public void addPlayer(String name,String surname,int ageInYears,int heightInCm,int weightInKg,int goals, int games)
            this.name= name;
            this.surname= surname;
            this.ageInYears= ageInYears;
            this.heightInCm= heightInCm;
            this.weightInKg= weightInKg;
            this.goals= goals;
            this.games= games;
            playerList.add(new Player(name,surname,ageInYears,heightInCm,weightInKg,goals,games));
            int z= playerList.size();
            System.out.println(z);
    }Many thanks for any help or suggestions

    but I still get a null pointer exception at the line
    playerList.add(new Player(name,surname,ageInYears,heightInCm,weightInKg,goals,games));The only scenario I can think of for a NullPointerException to be thrown by this statement is that playerList is null...
    (And I can't understand how something could actually be added in the list in this case...)
    Are you sure the exception is thrown at this line? Maybe you could post updated code, and the stack trace.
    On another note, I have a class Goalkeeper which extends from Player ( which has extended from person).
    Will I be able to add a Goalkeeper into the List even though it expects an Player object?You can add any instance of Player or subclass of Player, so it won't be a problem to add goalkeepers. (Did you try?)
    (a Goalkeeper is a Player)

  • ArrayList Error on Index

    This is my code;
    * Main2.java
    * Created on 09 February 2007, 14:40
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package testing;
    * @author Administrator
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.ListIterator;
    * @author Administrator
    public class Main2 {
        Connection conn=null;
        Statement stmt=null;
        ResultSet rsBankName=null;
        int valid,invalid,total;
        /** Creates a new instance of Main */
        public Main2() {
            connectOracle();
            readCards(2007,1,31);
            //System.out.println(checkDate(""));
         * @param args the command line arguments
        public void connectOracle(){
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@IP:SID", "user", "pwd");
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {}
        public void readCards(int year,int month,int day){
            String bankCode="";
            ArrayList<String> bname=new ArrayList<String>(10);
            try {
                rsBankName=stmt.executeQuery("select bank_code,bank_name from bank");
                rsBankName.first();
                do{
                    bname.add(rsBankName.getInt("bank_code"),rsBankName.getString("bank_name"));
                }while(rsBankName.next());
            } catch (SQLException ex) {
                ex.printStackTrace();
            ListIterator li=bname.listIterator();
            while(li.hasNext()){
                System.out.println(li.next());
        public static void main(String[] args) {
            new Main2();
    }And I am getting this Stack trace
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.add(ArrayList.java:367)
    at testing.Main2.readCards(Main2.java:60)
    at testing.Main2.<init>(Main2.java:36)
    at testing.Main2.main(Main2.java:71)
    I search for it on the net, it say it has a bug and it was version 1.2 and I am using the new version of JDK 1.6.
    Any idea what is going wrong.

    D'OH!!
    You can't add an element at a specific index unless
    there is already something at that index ? WTF? This
    is strange behavior, What is even odder is that you can expand by one with "add", just not greater than that.
         ArrayList<Integer> thingies = new ArrayList<Integer>(10);
         for(int i = 0; i< 10; i++ ) {
             thingies.add( i, i );
         System.out.println( thingies );works, but
         ArrayList<Integer> thingies = new ArrayList<Integer>(10);
         for(int i = 9; i>0; i-- ) {
             thingies.add( i, i );
         System.out.println( thingies );does not.
    even though I will say that
    there are other classes you could use instead. Try a
    HashMap<Integer,String> Or if the size is fixed, use an array.

  • Arraylist.add() problem

    Hi,
    I'm trying to read a CSV text file into an arraylist.
    I can read the text file fine, its just when it gets to the actual arraylist.add() part it just .. .. doesn't work. It can print the values from the CSV file no problem. I'm sure my syntax is fine, everything compiles. I've read it and double checked it and checked it again.
    It just doesn't work .. I don't know why.
    The arraylist I am trying to read into is
    ArrayList<Customer> customers = new ArrayList<Customer>();Within other parts of the program I can read in dummy data, eg
    customers.add(new Customer(01, "Jims Mowing", "16 Long Grass Street", "Thorndale", "123-4567", "[email protected]"));
    but suffice to say, yes, it is kaput.
       * READING THE CUSTOMER TEXT FILE INTO THE ARRAY LIST
      private void custFileToArray ()
        RectangleTUI results = new RectangleTUI(); // create results object
        try   
          BufferedReader inputStream = new BufferedReader(new FileReader(PATHNAME + CUSTFILE));
          System.out.println("Contents of file: " + CUSTFILE); // print heading
          String line = inputStream.readLine(); // read first line
          while (line !=null) // test for end of file (EOF)
            results.loadCustFile(line);       
            line = inputStream.readLine(); // read next line
          // close file
          inputStream.close();
        // catch any file open errors
        catch(FileNotFoundException e)
          System.out.println("Error opening file: " + CUSTFILE);
          System.exit(0);
        catch(NoSuchElementException e)
          System.out.println("ATTENTION: One or more " + CUSTFILE + " records are missing data");
        // catch any file reading errors
        catch(IOException e)
          System.out.println("Error reading from file: " + CUSTFILE);
          System.exit(0);
        System.out.println("File Reading Complete");  
      private void loadCustFile(String textLine)
        String delimiters = ","; // set tokenizer delimiter
        StringTokenizer RecordFields = new StringTokenizer(textLine,delimiters);  
        int cidNum = Integer.parseInt(RecordFields.nextToken()); // Customer ID
        System.out.println(cidNum + " Hello I am a stupid piece of code. I don't like to work properly");
        String cName = RecordFields.nextToken();   // Name
        String cAdd = RecordFields.nextToken();   // Street Address
        String cBurb = RecordFields.nextToken();   // Suburb
        String cPhone = RecordFields.nextToken();   // Phone
        String cEmail = RecordFields.nextToken();   // Email
        customers.add(new Customer(cidNum, cName, cAdd, cBurb, cPhone, cEmail));
      }

    Cowzor wrote:
    Hi,
    Cheers for the replies & the printStackTrace tip.
    The thing is it's not actually throwing up any errors or crashing. It's acting as if everything is AOK - but since it then says there's nothig in the arraylist there must be a problem ... somewhere.
    Sorry if I've mis-understood what you were saying
    Here's the dummy data I'm using just incase it's at all relevant
    200701,Jims Mowing,16 Long Grass Street,Thorndale,123-4567,[email protected]
    200702,Chevy Racers,2 Raceway Drive,Boganville,123-4567,[email protected]
    200703,Renta Dent,82 Airport Oaks Road,Airport Oaks,123-4567,[email protected]
    200704,Discount Taxis,8 Poor Place,Otara,123-4567,[email protected]
    u split contains of CSV file on basis of , (comma) and read it

  • ArrayList() problems

    Hi!
    I need a little help getting an ArrayList to work. I am refactoring some of the classes in one of the O'Reilly books for a class assignment. I believe that I cannot get my ArrayList to add elements into itself. I'm not quite sure what I'm doing wrong. I'll post the code below. The problem arises in the last part of the code (at least I think it does) where i can't get my variable "size" (see the "for loop" below) to be resolved. I have tried initializing the variable at the beginning of the entire class in which case I can get the file to compile to a class. But when I run the class, I still get an ArrayOutOfBounds exception letting me know that my array is still initialized to 1 when i believe that and my index is a larger number (the number I input into the console). the message I get from the command line is:
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Error:
    java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(ArrayList.java:326)
    at MyFactorial.computeFactorialCacheB(MyFactorial.java:115) // this would be the second line of the "for" loop
    at MyFactorial.main(MyFactorial.java:134)
    Any help would be greatly appreciated. Thanks in advance.
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    Here is my code
         public static synchronized BigInteger computeFactorialCacheB(String s) {
         private static int size;
    ArrayList table = new ArrayList();
              table.add(BigInteger.valueOf(1));
              int x = 0;
              try {
                   x = Integer.parseInt(s);
              catch (NumberFormatException e) {
                   System.out.println("the number you enter must be an integer");
              if (x<0) {
                   throw new IllegalArgumentException("x must not be a negative number");     
              else {
                   for(int size = table.size(); size <= x; size++);{
                        BigInteger lastfact = (BigInteger)table.get(size-1);
                        BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
                        table.add(nextfact);
              return (BigInteger) table.get(size-1);
         }

    Thanks for your reply.
    As I said in my original posting, I am refactoring code from one of the O'Reilly books for an assignment. So no, this isn't all my code, just some of it (copyright is duly noted in my assignment).
    The semicolon was a great cach (thanks!) I truly didn't see it. The issue of the "size" variable is what I am trying to solve. When I originally entered the code int my IDE (eclipse) the first declaration of int size inside the for loop was OK but subsequent references to it (still in the for loop) wouldn't resolve.
         for(int size = table.size(); size <= x; size++){
               BigInteger lastfact = (BigInteger)table.get(size-1);
               BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
                    table.add(nextfact);Hence the experimentation with the "size" variable. The use of the ArrayList was one of the parameters of the assignment. I see what you mean by creating a new list each time. The purpose of the method is to return a factorial (n!) using a BigInteger. This loop is pretty much just as it came out of O'rilley. It seems to work fine in their rendition (I guess that's why they get to write books).
    Tanks so much for your help. I'll refactor again and repost (probably tomorrow).
    � regards!

  • ArrayList and double[]

    private double[] findAverageFace(ResultSet rs, int rows){
            String path;
            Scanner scanner;
            int picn = 0;
            double[] avgFace = new double[rows * rows];
            try{
                //System.out.println("scanning the result set");
                double[] pic;
                while(rs.next()){
                    path = rs.getString(1); //the path to the matrix
                    //System.out.println("path: " +path);
                    scanner = new Scanner (new File(path));
                    pic = new double[rows * rows];
                    for(int i=0; i<rows*rows; i++){
                        pic[i] = scanner.nextFloat();
                        avgFace[i] += pic;
    //lets add a clone of the pic array
    // k++;
    //System.out.println("\tmatrix: " + k);
    //matricesToolbox.MatrixToolbox.printMatrix(avgFace);
    facesArrayList.add(pic.clone());
    picn++;
    //System.out.println("pic n : "+ picn);
    for(int i=0; i<rows*rows; i++)
    avgFace[i] /= picn;
    return(avgFace);
    }catch(Exception e){
    e.printStackTrace();
    return(null);
    private ArrayList calculateDifferenceFaces(double[] avgFace){
    ArrayList xArrayList = new ArrayList();
    double[] pic;
    double[] phi = new double[avgFace.length];
    for(int i=0; i< facesArrayList.size(); i++){
    pic = (double[]) facesArrayList.get(i);
    for(int j=0; j< pic.length*pic.length; j++){
    System.out.println(pic[j] + " minus " + avgFace[j]);
    //System.out.println(avgFace[j] + "");
    phi[j] = pic[j] - avgFace[j];
    //System.out.print(phi[j] + " ");
    xArrayList.add(phi);
    return(xArrayList);
    }why in line "System.out.println(pic[j] + " minus " + avgFace[j]);" i get the same values for both pic and avgFace, although in the 1st method i add a clone of pic  facesArrayList.add(pic.clone()); ??                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I would suggest;
    - using a debugger. This will show if the arrays are the same or not. avgFace will be the same each time for each pics as its the same array.
    - use nextDouble() as nextFloat() is less accurate (I am guessing not a problem here)]
    - don't use pic.clone(), just create a new array at the start of each loop.

  • ArrayList problem

    Well, im new to ArrayList and im having great trouble trying to figure things out,
    this is what im supposed to do:
    The Problem
    A banking institution offers certificates of deposit (CD's) with a variety of interest rates, and maturities of 1, 3, 5, and 10 years. Interest is always compounded, daily, monthly, or quarterly.
    Write a Java program that will compute the accumulated value (principal plus interest earned), at yearly intervals, of any number of such CD's. Assume that a year always consists of exactly 365 days.
    Output will be a series of 10 annual reports:
    Reports will be in table form with appropriate column headings. There will be one row of the table for each active CD, which will include all the data along with the accumulated value and total interest earned to data.
    Each report will also print the total interest earned by all CDs for the current year, and total interest earned by all active CD�s to data.
    Once a CD reaches maturity, it will stop earning interest and will not appear in any future reports. E.g., a CD with a maturity of 5 years will appear in the reports for years one through five, but not thereafter.
    The CD Class
    Begin by creating a class to model a CD. Each CD object "knows" its own principal, interest rate, maturity, and compounding mode (private instance variables). The class has �get� methods to return this data and a method to compute and return the accumulated value.
    The CDList Class
    Now create a class to maintain a list of CDs. You will need methods to add a CD to the list and to print the annual report.
    The Driver (i.e., "Test") Class
    Your test class or "driver" class will read data for any number of CDs from a file that I will supply. Each line of the file will contain the data � principal, interest rate (as an annual per cent), maturity, and compounding mode � for one CD.
    First, tokenize each line read, create a CD object from the tokens, and add it to the list. Then print the reports.
    Additional Specifications
    Your CDList class must use an ArrayList as the principal (no pun intended) data structure.
    Your test class is to read the data file one time only. No credit will be given for programs that read the data file more than once.
    Make sure your program is well documented and adheres to the style conventions discussed in class.
    Due date:          Thursday, April 20th
    Formula
    The accumulated value (i.e., principal plus interest), A, is given by the formula:
                                                 r nt
                   A = p ( 1 + ���� )
                                                 n
                   where
    p = principal
    n = number of times compounded per year
    r = annual interest rate, expressed as a decimal
    t = elapsed time in years
    now, im supposed to read data from a file, and whats inside the file is:
    5000 5 8.25 quarterly
    12000 10 10.80 daily
    2000 5 7.30 quarterly
    10000 3 5.55 monthly
    2000 1 4.50 daily
    5000 10 9.15 monthly
    now, im totally lost, however, ive managed to do this so far:
    import java.util.ArrayList;
    import java.io.*;
    import java.util.*;
    class CD
         private String time;     
         private double cdAmount;
         private int cdMonths;
         private double cdInterest;
         public CD(String time, double cdAmount, int cdMonths, double cdInterest)
              this.time = time;
              this.cdAmount = cdAmount;
              this.cdMonths = cdMonths;
              this.cdInterest = cdInterest;     
         public String getTime()
              return time;
         public double CDAmount()
              return cdAmount;
         public int CDMonths()
              return cdMonths;
         public double CDInterest()
              return cdInterest;
    class CDlist
         private ArrayList<CD> list;
         public CDlist()
              list = new ArrayList<CD>();
         public void addList(CD info)
              list.add(info);
         }Please any help regarding this subject will be greatly appreciated.

    Ok, lets take this step by step,
    it says that in the cd class im supposed to have:
    Each CD object "knows" its own principal, interest rate, maturity, and compounding mode (private instance variables)"
    1. i have 4 variables, am i missing something in the CD class?
    2. the cdlist class is supposed to have this:
    "Now create a class to maintain a list of CDs. You will need methods to add a CD to the list and to print the annual report."
    i have created an empty list, do i need to add the 4 variables into the list ive created??
    3. the test class says this:
    "Your test class or "driver" class will read data for any number of CDs from a file that I will supply. Each line of the file will contain the data � principal, interest rate (as an annual per cent), maturity, and compounding mode � for one CD.
    First, tokenize each line read, create a CD object from the tokens, and add it to the list. Then print the reports."
    well i dont know how to do this, but ill try not to worry about this now

  • ArrayList and wrappers

    Can an ArrayList contain different types of objects from the same class?
    I know that it must be an object but can one be of type String and another be of type int?
    I am reading information from a file that looks something like this:
    Sam
    Jones
    21
    Tim
    Hendricks
    15
    I have written the following method:
    ArrayList list = new ArrayList();
    String fname;
    try
      BufferedReader br = new BufferedReader(new FileReader("student.txt"));
      while ((fname = br.readLine()) != null)
             String lname=br.readLine();
         int age= br.readLine();
         br.readLine(); //FOR THE BLANK LINE
         list.add(new Student(fname, lname, age));
      br.close();
    catch(IOException e)
      System.err.println(e.getMessage());
      System.exit(0);
    }If I declare age as type String the method and other methods work great, but I need to make it of type int.
    I have read up about wrappers and I think that is what I am suppose to use for the int but no matter what I do, I get tonnes of error messages.
    Any help would be appreciated.

    A better way would be to build a class for your data packet.
    class Thing {
      public final String name;
      public final int age;
      public Thing(String name, int age) {
        this.name = name;
        this.age = age;
    public class SomeClass {
      public static void main(String[] args) {
        List list = new ArrayList();
        list.add(new Thing("Jill",10));
        list.add(new Thing("John",20));
        list.add(new Thing("Janet",30));
        list.add(new Thing("Jeremy",40));
    }Then you can simply get your values back with
    for(Iterator iterator = list.iterator(); iterator.hasNext(); ) {
      Thing thing = (Thing) iterator.next();
      System.out.println("Name: "+thing.name);
      System.out.println("Age: "+thing.age);
    }Or something like that...
    Talden

Maybe you are looking for

  • How to clean the inside of a trackpad

    i have the newest macbook pro, with the battery that cannot be removed. i fel asleep with my laptop beside me and somehow during the night my drink spilled. i woke up and checked everything out and everything worked fine, except when i use the trackp

  • Why not a FAQ ?

    Using this forum I noticed that a lot of questions are similar and after a while (a month or so) they will appear again and again. I myself answered 3 times to the same question. Is it possible that the Oracle support organizes a FAQ on such subject

  • About Business Partner Marketing, Sales Area Data tables

    Hi, I want the table names where Business Partner sales area data and Marketing Attributes are stored. Thanks in advance. Regards, Dhanraj.

  • Maximum index key length exceeded

    Hi, I am getting following error on executing this command in MS SQL server 2012- Command - alter table <table1_name> add constraint <constraint name> foreign key (<column1 name>) references <table2_name>(<column2_name>) Error - System Error: #140002

  • Wireless bridge question....?

    Hi all, I have a wireless bridge between two buildings with 54 Mbps link. However theres around 90% packet loss between the two sites. What would be the best way to take care of packet loss.Any wireless experts..? Saurabh