Array set in constructor

Hello! I am a beginner. How to set to constructor
the size of the Record array.
Thanks for propable help!
public class CDRack {
  private Record[] collection;
  private int size;
/**Creates a new, empty CD rack.
Parameters:
size - the size of the new rack, i.e. the number of
slots it has */
    public CDRack(int size) {
}

Is this what you're trying to do?
public class CDRack {
private Record[] collection;
private int size;
/**Creates a new, empty CD rack.
Parameters:
size - the size of the new rack, i.e. the number of
slots it has */
public CDRack(int size) {collection = new Record[size];
this.size = size;

Similar Messages

  • Value  set in constructor is not getting saved in button  Action method

    Hi All,
    I am not understanding why the value set ( On Condition )in constructor is not hold in the button actoin method.
    Could any body explain me on that
    for this I will try to explain with sample example
    I have taken a button and add a integer property in session bean.
    now if session bean's property is even then I am trying to set the button value to bidNow other wise Accept Invitation.
    Till this opstion everything is OK
    but once I click on Button,
    Constructor is doing the right job only. But I do not understand why in button action I am getting the First Value only.
    public Page1() {
            // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
            try {
                if (getSessionBean1().getIntValue()%2==0)
                    button1.setValue("BidNow");
                else
                    button1.setValue("Accept Invitation");
                getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
                log("In Constructor Button Value : "+button1.getValue());
            } catch (Exception e) {
                log("Page1 Initialization Failure", e);
                throw e instanceof javax.faces.FacesException ? (FacesException) e: new FacesException(e);
            // </editor-fold>
            // Additional user provided initialization code
        public String button1_action() {
            // TODO Replace with your code
            log("In Action Button Value : "+button1.getValue());
            return null;
        }and here is the log
    [#|2005-07-19T11:55:17.859+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:17.859+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:18.359+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:18.359+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:18.843+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:18.843+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:19.312+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:19.312+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:19.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:19.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:20.234+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:20.250+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:20.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:20.828+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:21.328+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:21.328+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:35.437+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:35.437+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:35.906+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:35.921+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:36.265+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:36.265+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:36.890+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:36.890+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:37.171+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : BidNow|#]
    [#|2005-07-19T11:55:37.171+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]
    [#|2005-07-19T11:55:37.468+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Constructor Button Value : Accept Invitation|#]
    [#|2005-07-19T11:55:37.468+0530|INFO|sun-appserver-pe8.0.0_01|javax.enterprise.system.container.web|_ThreadID=14;|WebModule[/webapplication12]In Action Button Value : BidNow|#]As per this log every time I am getting Bid Now only in action, though the value is changed in Construtcor
    Can u explain the reason for this

    Hi Sudhakar,
    Please try the following and you will get an idea as to what is happening:
    1. Drag and drop a button, 2 outputText components
    2. Add a property to the session bean called intValue of type int. Customize it to set it's initial value to 0
    3. Add the following lines of code to the constructor
    outputText1.setValue("" + getSessionBean1().getIntValue());
    getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
    4. Double click on the button component to go to the button action method.
    5. Add the following line of code
    outputText2.setValue("" + etSessionBean1().getIntValue());
    6. Save and run the application
    7. Watch the values of outputText1 and outputText2 with each click of the button
    Also, try the application with the following code block in the button action method:
    if(getSessionBean1().getIntValue()%2==0){
    button1.setValue("Bid Now");
    } else{
    button1.setValue("Accept Invitation");
    getSessionBean1().setIntValue(getSessionBean1().getIntValue()+1);
    outputText1.setValue(button1.getValue());
    outputText2.setValue("" + getSessionBean1().getIntValue());
    When the above code block is in the button action method the values set to button are as expected.
    Hope that helps
    Cheers
    Giri :-)

  • Easier way to set post-constructor JTable column names?

    I have a class that extends JTable. It also has a pair of inner classes that extend DefaultTableCellRenderer and AbstractTableModel so I can dynamicaly adjust the number of rows and their contents. That's not the problem - that part works fine. The problem is the column headers. My table doesn't currently have any but I want to add them.
    The column quantity is constant at 3 and should always be the same 3 Strings. It would be nice if I could use the JTable constructors that take a Vector or Object[] of column names from the start in my new class' constructor. But I don't think I can because at that point I don't know how many rows there will be or what they'll contain. Trying to set rowData to null just caused runtime exceptions.
    So the alternative seems to be to call setColumnModel() within the constructor, passing it a DefaultTableColumnModel. Which then requires I call addColumn() three times. Each time passing it a new TableColumn object. Each of which requires that I separately call setHeaderValue() after I construct it to set the header name. Am I right in that is the only way to do it? It just seems overly complex.

    I'll post a streamlined version of my class in case that will help...
    public class TotalsTable extends JTable
       private static int NUM_COLUMNS = 3;
       static final public String columnNames[] = {
             "Col Name 1", "Col Name 2", "Col Name 3"};
       protected Vector data = null;
       private TotalsModel tableModel;
       public TotalsTable()
          tableModel = new TotalsModel();
          setModel(tableModel);
          TableCellRenderer renderer = new TotalsCellRenderer();
          setDefaultRenderer(Object.class, renderer);
       public void updateTable(Vector pData)
          data = pData;
          tableModel.update();
       class TotalsCellRenderer extends DefaultTableCellRenderer
          public Component getTableCellRendererComponent
             (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
             super.getTableCellRendererComponent(table, value, isSelected,
                                                 hasFocus, row, column);
             if (column == 0) {
                setForeground(Color.blue);
             else {
                setForeground(Color.black);
             return this;
       class TotalsModel extends AbstractTableModel
          public TotalsModel()
             super();
          protected void update()
             fireTableStructureChanged();
           * Retrieves number of columns
           * (Necessary for AbstractTableModel implementation)
          public synchronized int getColumnCount()
             return NUM_COLUMNS;
          public synchronized int getRowCount()
             if (playerData == null)
                System.out.println("No rows found in table");
                return 0;
             else
                return playerData.size();
           * Returns cell information of a record at location row,column
           * (Necessary for AbstractTableModel implementation)
          public synchronized Object getValueAt(int row, int column)
             try
                MyObject p = (MyObject) data.elementAt(row);
                switch (column)
                   case 0:
                      return p.getName();
                   case 1:
                      return ("" + p.getDataItem2());
                   case 2:
                      return ("" + p.getDataItem3());
                   default:
                      System.out.println("getValueAt() Error: Invalid column");
             catch (Exception e)
                System.out.println("Exception in getValueAt(): " +
                                   e.getMessage());
             return "";
          public String getColumnName(int col)
             if (col < NUM_COLUMNS)
                return columnNames[col];
             else
                return "";
          public Class getColumnClass(int c)
             return getValueAt(0, c).getClass();
    }

  • MovieClip Not Recognizing Properties Set in Constructor FP 11.8.800.115 (Chrome)

    Hi,
    In making a subclass from MovieClip in Flash ActionScript 2.0, I set the _alpha and _visible values to 0 and false respectively.  I do this so that I can make sure all instances within the MovieClip render before I animate them with ActionScript.  So, after 1 frame has rendered I set the _alpha and _visible back to 100 and true respectively, and then proceed to animate them.
    I'm finding that in Google Chrome (Flash Player 11.8.800.115) the values I set in the construtor are being ignored!  This does not happen in any other browser including Mozilla FireFox (Flash Player 11.8.800.94).
    This needs an urgent fix!
    I'm publishing for Flash Player 8.
    Thanks!
    -Cowboy

    Hi,
    In making a subclass from MovieClip in Flash ActionScript 2.0, I set the _alpha and _visible values to 0 and false respectively.  I do this so that I can make sure all instances within the MovieClip render before I animate them with ActionScript.  So, after 1 frame has rendered I set the _alpha and _visible back to 100 and true respectively, and then proceed to animate them.
    I'm finding that in Google Chrome (Flash Player 11.8.800.115) the values I set in the construtor are being ignored!  This does not happen in any other browser including Mozilla FireFox (Flash Player 11.8.800.94).
    This needs an urgent fix!
    I'm publishing for Flash Player 8.
    Thanks!
    -Cowboy

  • Calendar reporting different date to that set in constructor

    Hi all, can anyone explain why when setting the date in the contstructor as 1/12/2007 and reading back out to the screen it is read out as "1 / 0 / 2008" ?
    Here's the code:
    Calendar calendar = new GregorianCalendar(2007,12,1);
              int defaultdate = calendar.get(Calendar.DAY_OF_MONTH);
              int defaultmonth = calendar.get(Calendar.MONTH);
              int defaultyear = calendar.get(Calendar.YEAR);
              System.out.println("Default date = "+defaultdate+" / "+defaultmonth+" / "+defaultyear);
              System.out.println("Timezone = "+calendar.getTimeZone());OUTPUT:
    Default date = 1 / 0 / 2008
    Timezone = sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=360
    0000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europ
    e/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,st
    artMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMod
    e=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]
    Cheers in advance for any advice on this.

    Months are zero-based, January is 0, ..., December is 11. You can use
    the symbolic constant:
    new GregorianCalendar(2007, Calendar.DECEMBER, 1);

  • Objects in a set

    Hi im writing a program that holds names in a a class like
    public class UserInfo
       private Set<String> Names= new HashSet<String>();
        * Constructor for objects of class UserInfo
       public UserInfo(String text)
          Names = text;
        * returns the values of Names to the receiver.
       public Set<String> getNames()
          return Names;
    }really basic im having the problems with a second class that holds the instances of this class.
    the second class has
    public class seach
       Set<objects> nameshold;
       public seach()
           nameshold= new HashSet<object>();     
        * adds the arument to the nameshold Set.
       public void addSite(Object Names)
          nameshold.add(Names);
       public void Seach(String aArument)
          for (object eachObject : nameshold)
             eachObject.contains(aArument);
    }it all works but i can not access the objects held by nameshold i guess its because its held in an object so i can't access it like a set
    but how would i access the sets in the nameshold object.
    this code i just write to show my problem so it may be full of bugs
    Edited by: Kiith on Mar 18, 2008 12:53 PM

    sorry this is the code i have its for college so no telling me how to but and im using bluej
    First class
    import java.util.*;
    public class Names
       private Set<String> groupNames = new HashSet<String>();
       public Names(String text)
          groupNames = Names.breakWords(text); 
       public Set<String> getgroupNames()
          return groupNames;
       public static Set<String> breakWords(String text)
          String[] Array;
          Set<String> brokenWords = new HashSet<String>();
          Array = text.split(" ");
          for (String eachWord : Array)
             brokenWords.add(eachWord);
          return brokenWords;
    }second class
    import java.util.*;
    public class seacher
       Set<Object> scannedNames;
       public seacher()
           scannedNames = new HashSet<Object>();     
       public void addGroup(Object groupNames)
          scannedNames.add(groupNames);
       public void searchFor(String aArument)
          for ( Object eachGroup : scannedNames)
             //eachGroup.contains("dan");                 
    }and i am using Object here i could use names instead but im not shore if that would make a differance
    this part is where im having problems //eachGroup.contains("Luke"); im trying to break down the group objects of names so i can test it
    one at a time so each object i can check if it holds the name "dan"
    when i run this code i have 2 instances of names called test1 and test 2 an instace of seacher called seach that hold both test1 and test2
    i what to check the value that are held in test1 and test2 to so see if it holds the value dan or any value. both test1 and 2 hold "pual", "dan", "mark"
    i do not know what they will hold in the end but for testing i use them.
    Edited by: Kiith on Mar 18, 2008 1:16 PM
    Edited by: Kiith on Mar 18, 2008 1:17 PM
    Edited by: Kiith on Mar 18, 2008 1:27 PM

  • Help Request! Static Array Objects.

    Hi, I'm a newbie looking for help with creating a static object array in the constructor of a class so the array can be accessed from all other classes but remains the same set of values for manipulation.
    My code looks like;
    public class ShipDatabase
    public static Ship shipList[];
    static {shipList[0] = new Ship("Sentry", 15, 10, "Scout");
    " " " etc
    shipList[5] = new Ship("Guard", 20, 2, "Scout");}
    However it won't compile. Also I need to know how to access it from other classes when it does compile.
    Any help is good help.

    eg?
    public class ShipDatabase
          private static class Ship
             private String s = null, ss = null;
             private int i = -1, j = -1;
             public Ship( String s, int i, int j, String ss )
                this.s = s;
                this.ss = ss;
                this.i = i;
                this.j = j;
             public String toString()
                return s + ", " + ss + ", " + i + ", " + j;
          public static Ship shipList[] = new Ship[]
          new Ship("Sentry", 15, 10, "Scout"),
          new Ship("Guard", 20, 2, "Scout")
          public static void main( String[] args )
          for( int i = 0; i < shipList.length; i++ )
             System.out.println( "sl: " + shipList[ i ] );
    }

  • Two array objects compareTo:

    Have two arrays: ttt and ppp. I have to have a method to compare them.
    public int compareTo(object ob)
    both of the arrays are int type and both have super long numbers in them.
    Thanks

    Actually, the reflection api is pretty fast since
    JDK1.4.0...No. Reflection could not be fast. In J2SDK1.4 it seems to be faster then in previous releases. But improvments do not include array operations. So here are some results of simple benchmark:
    bash-2.05a$ /usr/java/jdk1.3.1_04/bin/java TestArray
    Result for reflect copiing (3 elements, 1000000 times): 4915ms
    Result for system copiing (3 elements, 1000000 times): 460ms
    Result for pure java copiing (3 elements, 1000000 times): 137ms
    bash-2.05a$
    bash-2.05a$ /usr/java/j2sdk1.4.0_01/bin/java TestArray
    Result for reflect copiing (3 elements, 1000000 times): 6082ms
    Result for system copiing (3 elements, 1000000 times): 491ms
    Result for pure java copiing (3 elements, 1000000 times): 115ms
    bash-2.05a$
    bash-2.05a$ /usr/java/j2sdk1.4.1/bin/java TestArray
    Result for reflect copiing (3 elements, 1000000 times): 5738ms
    Result for system copiing (3 elements, 1000000 times): 497ms
    Result for pure java copiing (3 elements, 1000000 times): 157ms
    bash-2.05a$
    As you can see, in new Java reflect operations on arrays are even slower then in jdk1.3.1. System copiing is good alternative for pure java (element by element) copiing, espetially for big arrays. And here is the code of this benchmark, test it on your PC also:
    import java.lang.reflect.*;
    public class TestArray {
        static void doNothing(){}
        static int field;
        public static void main(String[] args) throws Exception {
            final int COUNT = 3, TIMES = 1000*1000;
            final String[] arr1 = new String[COUNT];
            final String[] arr2 = new String[COUNT];
                long time = -System.currentTimeMillis();
                for(int i=TIMES; i-->0;)
                    copyReflect(arr1, arr2, COUNT);
                time += System.currentTimeMillis();
                System.out.println("Result for reflect copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
                long time = -System.currentTimeMillis();
                for(int i=TIMES; i-->0;)
                    copySystem(arr1, arr2, COUNT);
                time += System.currentTimeMillis();
                System.out.println("Result for system copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
                long time = -System.currentTimeMillis();
                for(int i=TIMES; i-->0;)
                    copyPureJava(arr1, arr2, COUNT);
                time += System.currentTimeMillis();
                System.out.println("Result for pure java copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
        private static void copyReflect(Object src, Object dst, int count) {
            for(int i=count; i-->0; ) Array.set(dst, i, Array.get(src, i));
        private static void copySystem(Object src, Object dst, int count) {
            System.arraycopy(src, 0, dst, 0, count);
        private static void copyPureJava(String[] src, String[] dst, int count) {
            for(int i=count; i-->0; ) dst[i] = src;

  • Lots of blank space when printing array with only last element printed

    I have a slight problem I have been trying to figure it out for days but can't see where my problem is, its probably staring me in the face but just can't seem to see it.
    I am trying to print out my 2 dimensional array outdie my try block. Inside the trying block I have two for loops in for the arrays. Within the second for loop I have a while to put token from Stringtokeniser into my 2 arrays. When I print my arrays in this while bit it prints fine however when I print outside the try block it only print the last element and lots of blank space before the element.
    Below is the code, hope you guys can see the problem. Thank you in advance
       import java.io.*;
       import java.net.*;
       import java.lang.*;
       import java.util.*;
       import javax.swing.*;
       public class javaflights4
          public static final String MESSAGE_SEPERATOR  = "#";
          public static final String MESSAGE_SEPERATOR1  = "*";
          public static void main(String[] args) throws IOException
             String data = null;
             File file;
             BufferedReader reader = null;
             file = new File("datafile.txt");
             String flights[] [];
                   //String flightdata[];
             flights = new String[21][7];
             int x = 0;
                   //flightdata = new String[7];
             int y = 0;
             try
                reader = new BufferedReader(new FileReader(file));   
                //data = reader.readLine();   
                while((data = reader.readLine())!= null)   
                   data.trim();
                   StringTokenizer tokenised = new StringTokenizer(data, MESSAGE_SEPERATOR1);
                   for(x = 0; x<=flights.length; x++)
                      for(y = 0; y<=flights.length; y++)
                         while(tokenised.hasMoreTokens())
                            //System.out.println(tokenised.nextToken());
                            flights [x] [y] = tokenised.nextToken();
                            //System.out.print("*"+ flights [x] [y]+"&");
                   System.out.println();
                catch(ArrayIndexOutOfBoundsException e1)
                   System.out.println("error at " + e1);
                catch(Exception e)
                finally
                   try
                      reader.close();
                      catch(Exception e)
             int i = 0;
             int j = 0;
             System.out.print(flights [j]);
    //System.out.println();

    A number of problems.
    First, I bet you see a lot of "error at" messages, don't you? You create a 21x7 array, then go through the first array up to 21, going through the second one all the way to 21 as well.
    your second for loop should go to flights[x].length, not flights.length. That will eliminate the need for ArrayIndexOutOfBounds checking, which should have been an indication that you were doing something wrong.
    Second, when you get to flights[0][0] (the very first iteration of the inner loop) you are taking every element from the StringTokenizer and setting flights[0][0] to each, thereby overwriting the previous one. There will be nothing in the StringTokenizer left for any of the other (21x7)-1=146 array elements. At the end of all the loops, the very first element in the array (flights[0][0]) should contain the last token in the file.
    At the end, you only print the first element (i=0, j=0, println(flight[ i][j])) which explains why you see the last element from the file.
    I'm assuming you have a file with 21 lines, each of which has 7 items on the line. Here is some pseudo-code to help you out:
    count the lines
    reset the file
    create a 2d array with the first dimension set to the number of lines.
    int i = 0;
    while (read a line) {
      Tokenize the line;
      count the tokens;
      create an array whose size is the number of tokens;
      stuff the tokens into the array;
      set flights[i++] to this array;
    }

  • How do I determine what element in an array was right clicked on?

    I have an array set up on my front panel. When the user right clicks on an element in that array, I would like them to be able select from 3 different options. I have the shortcut menu working, but I need to know which element in the array the user right clicked on to determine what values to change. How can I get the index of the element?
    Thanks for any help!
    Solved!
    Go to Solution.

    Couldn't you get index values from the array property node?
    Also this doesn't account for if scrollbars are seen or not.  And I usually like to know if my range is valid, because again I could be clicking on a scrollbar, or label and still get the Mouse Down event.
    Here is one I posted a while ago.
    http://forums.ni.com/t5/LabVIEW/Interesting-way-to-detect-array-index-from-mouse-position/m-p/286841...
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.

  • Converting object wrapper type array into equivalent primary type array

    Hi All!
    My question is how to convert object wrapper type array into equivalent prime type array, e.g. Integer[] -> int[] or Float[] -> float[] etc.
    Is sound like a trivial task however the problem is that I do not know the type I work with. To understand what I mean, please read the following code -
    //Method signature
    Object createArray( Class clazz, String value ) throws Exception;
    //and usage should be as follows:
    Object arr = createArray( Integer.class, "2%%3%%4" );
    //"arr" will be passed as a parameter of a method again via reflection
    public void compute( Object... args ) {
        a = (int[])args[0];
    //or
    Object arr = createArray( Double.class, "2%%3%%4" );
    public void compute( Object... args ) {
        b = (double[])args[0];
    //and the method implementation -
    Object createArray( Class clazz, String value ) throws Exception {
         String[] split = value.split( "%%" );
         //create array, e.g. Integer[] or Double[] etc.
         Object[] o = (Object[])Array.newInstance( clazz, split.length );
         //fill the array with parsed values, on parse error exception will be thrown
         for (int i = 0; i < split.length; i++) {
              Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
              o[i] = meth.invoke( null, new Object[]{ split[i] });
         //here convert Object[] to Object of type int[] or double[] etc...
         /* and return that object*/
         //NB!!! I want to avoid the following code:
         if( o instanceof Integer[] ) {
              int[] ar = new int[o.length];
              for (int i = 0; i < o.length; i++) {
                   ar[i] = (Integer)o;
              return ar;
         } else if( o instanceof Double[] ) {
         //...repeat "else if" for all primary types... :(
         return null;
    Unfortunately I was unable to find any useful method in Java API (I work with 1.5).
    Did I make myself clear? :)
    Thanks in advance,
    Pavel Grigorenko

    I think I've found the answer myself ;-)
    Never thought I could use something like int.class or double.class,
    so the next statement holds int[] q = (int[])Array.newInstance( int.class, 2 );
    and the easy solution is the following -
    Object primeArray = Array.newInstance( token.getPrimeClass(), split.length );
    for (int j = 0; j < split.length; j++) {
         Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
         Object val = meth.invoke( null, new Object[]{ split[j] });
         Array.set( primeArray, j, val );
    }where "token.getPrimeClass()" return appropriate Class, i.e. int.class, float.class etc.

  • Object Array Data Provider Refresh Possible bug

    Hello
    I am having a problem with Object Array Data Provider in terms that the table's data is not changed corectly after a request as expected, but after two requests.
    Steps to reproduce the bug:
    0. Create a new Visual Web project, call it 'test'.
    Set 'Bundled Tomcat ' or 'Sun 9' as deploy target server.
    Edit 'Page1' of the project.
    1. Create an Entity class, simple class that has only getters and setters with a few fields (lets say 'id' and 'name').
    2. In the SessionBean1 that is generated by the framework create an array of Entity class named 'entityArr', and getters and setters for this field.
    3. Add a new Array Object Data Provider on the page and set in its properties as array the array created in the previous step 'entityArr (SessionBean1)'.
    4. Add a new table component, and set as data provider the provider created in step 3.
    In the Table's Layout map the fields from the Entity class, and set whatever compnents you desire for each component's type or leave the default ones (Static Text).
    5. Add a 'property change trigger component' on the page. I called it like this because I tried the following :
    5.1 A text field and a button to submit the text value
    5.2 A Calendar component with autosubmit
    5.3 A DropDown with autosubmit.
    6. On the property change trigger component created at step 5 set a value_changed method that changes the the array that should be displayed by the table.
    For Example, for a DropDown component, you will have a method like this :
    public void dropDown1_processValueChange(ValueChangeEvent event) {
    String idStr = (String) event.getNewValue();
    System.out.println("Entity id :"+idStr);
    if(idStr .equals("item1")) {
    fillSessionBean1(true);
    else {
    fillSessionBean1(false);
    getSessionBean1().setItemName(idStr);
    private void fillSessionBean1(boolean fillValues) {
    Entity[] values ;
    if(fillValues) {
    values = new Entity[4];
    for ( int i=0;i<values.length; i++) {
    Entity entity = new Entity();
    entity.setDescription("Description "+i);
    entity.setName("Name "+i);
    entity.setId(i) ;
    values[i] = entity;
    else {
    //values = new Entity[0];
    values = null;
    getSessionBean1().setEntityArr(values);
    7. When running the program, if the selected is Item1, the table does not show the array set if on this branch.
    I am using :
    Netbeans 5.5 build 20061017100,
    Visual Web Pack 070104_2,
    Ent.Pack 20061212
    jdk 1.6.0
    Operating Systems : Both Linux Suse10 and Windows.
    If anyone has a solution for this please let me know.

    OK
    While no one responded, I had to think for myself.
    There is a bug in the code generated by netbeans or there is nowhere specified that if you attach an array to a data provider you will have to notify by hand the data provider that the array has changed.
    You will have to put this line that is generated in init function in your valuechanged functions :
    objectArrayDataProvider1.setArray((java.lang.Object[])getValue("#{SessionBean1.entityArr}"));
    I think this aproach is a little bit wrong, even it works.
    I believe the data provider should be notified the array has been changed.
    There could be a much more simple aproaches :
    1. In the code generated by netbeans, if you attach an array to a data provider the data provider will be notified after any set(Object[])
    2. The data provider could have a function so you will ne anle to attach to the data provider an Object (the session bean, in my case) and the name of the function that retrieves the array (in my case, 'getEntityArr') .
    The code generated by netbeans could add this function easily.
    Maybe there are any other better aproaches, and I might be wrong.
    It's good that it works.

  • Another set of eyes

    I could use a second look. Why is name outputting null rather than "no name yet?"
    import java.util.Scanner;
    public class Exercise5
        public static void main(String[] args)
           //Create the contructors
            Species species1 = new Species();
            Species species2 = new Species();
            Species species3 = new Species();
            //Output the initial values of the three constructors
            System.out.println("==================== Initial Values ====================");
            System.out.println("\nSpecies 1");
            species1.writeOutput( );
            System.out.println("\nSpecies 2");
            species2.writeOutput( );
            System.out.println("\nSpecies 3");
            species3.writeOutput( );
    import java.util.Scanner;
    Class for data on endangered species.
    public class Species
        private String name;
        private int population;
        private double growthRate;
        public void readInput( )
            Scanner keyboard = new Scanner(System.in);
            System.out.println("What is the species' name?");
            name = keyboard.nextLine( );
            System.out.println(
                          "What is the population of the species?");
            population = keyboard.nextInt( );
            while (population < 0)
                System.out.println("Population cannot be negative.");
                System.out.println("Reenter population:");
                population = keyboard.nextInt( );
            System.out.println("Enter growth rate (% increase per year):");
           growthRate = keyboard.nextDouble( );
        public void writeOutput( )
             System.out.println("Name: = " + name);
             System.out.println("Population: = " + population);
             System.out.println("Growth rate: = " + growthRate + "%");
         Precondition: years is a nonnegative number.
         Returns the projected population of the calling object
         after the specified number of years.
        public int predictPopulation(int years)
              int result = 0;
            double populationAmount = population;
            int count = years;
            while ((count > 0) && (populationAmount > 0))
                populationAmount = (populationAmount +
                              (growthRate / 100) * populationAmount);
                count--;
            if (populationAmount > 0)
                result = (int)populationAmount;
            return result;
        public void setSpecies(String newName, int newPopulation,
                               double newGrowthRate)
            name = newName;
            if (newPopulation >= 0)
                population = newPopulation;
            else
                System.out.println("ERROR: using a negative population.");
                System.exit(0);
            growthRate = newGrowthRate;
        public String getName( )
            return name;
        public int getPopulation( )
            return population;
        public double getGrowthRate( )
            return growthRate;
        public boolean equals(Species otherObject)
            return (name.equalsIgnoreCase(otherObject.name)) &&
                   (population == otherObject.population) &&
                   (growthRate == otherObject.growthRate);
        //set the default species constructor
        public void Species ()
              String name = "No name yet";
              int population = 0;
              double growthRate = 0.0;
         //set a constructor using just the initialName
         public void Species(String initialName)
              String name = initialName;
              int population = 0;
              double growthRate = 0.0;
         //set a constructor using initialName and initialPopulation
         public void Species(String initialName, int initialPopulation, double initialGrowthRate)
              String name = initialName;
              int population = initialPopulation;
              double growthRate = initialGrowthRate;
    }

    warnerja wrote:
    public void Species ()And don't forget the other hint: The above is NOT defining a constructor. It is defining a method named "Species", which you never invoke, so even if you just change the code as suggested so far, you'll still have a null.<GRUMBLE>
    ... and in my humble opinion both these "common problems" should result in compiler warning.
    public void Species ()
                        ^
    STYLE_WARNING: The 'public void Species()' method has the same name as the containing class, making it look like a
    constructor. This method name is confusing to other programmers, and is a likely cause of future bugs. This is
    most commonly a mistake. If you meant 'Species()' to be a constructor then remove the return type. If you
    meant this to be a method then you should rename it.
        String name = "No name yet";
        ^
    STYLE_WARNING: The local variable 'name' hides the class attribute of the same name (this.name). This is confusing,
    especially to other programmers, and is a common cause of bugs. Consider renaming the local variable, or
    the attribute.</GRUMBLE>

  • Can the Ring Properties/Edit Items/Labels be populated by array values?

    Can the Ring Properties/Edit Items/Labels be populated by array values?
    I'm trying to troubleshoot an existing LabView 7.0 application at our office (this is only the beginning of my nightmare) and I'm finding that there is an array being created out of discrete Elements, which is then being indexed using the Indexed Array function, using a Ring control as the Index input. 
    What I'm seeing is that whoever created this "Appication" seems to require that any new 'elements' that need to be added to the array need to added in AT LEAST two locations (add the element to the array and add a label on the Edit Items tab of the Ring control used to index the array) and there may be more locations I haven't found that also needs the same information.  Since I can't see any way for the array and the ring control to 'compare' the text strings, I'm assuming the array is being indexed using the 'values' from the Edit Items tab.  Ths would allow different text in the Ring dropdown than is actually contained in the text of the array.
    This is contrary to most of the coding practices I've learned, so I'm wondering if I could use the text strings contained in the array itself to populate Item list in the Ring control?
    Later I can create an 'entry form' that would allow new parts to be added by staff that doesn't require knowledge of LabView programming. (The "Users" should NEVER have to see the underlying block diagrams/code to add or edit parts ot test parameter values.)
    Thanks

    In 8.2 you can do this with a property node and the "Strings [ ] Property".  It accepts an array of strings.  Order of strings in array sets the order in the control.  Should work in 7.0 as well.

  • What is the use of the setter dependency injection in Spring?

    What is the use of the dependency setter injection ?
    In a database driven app, I retrieve results, use the javabeans set methods to save stuff in javabeans and then call get on it.
    What is the use of having something set externally from a xml already ?
    Can someone provide an example when the setter injection can be used?
    I wouldnt imaginge using it to get usernames, passwords, databaseurl because we use JNDI for that...
    Is the dependency setter meant as something additional to web.xml so you dont have to get params from web.xml?

    No, you would indicate in the XML that the Hibernate object and the TransactionFactory (I am being vague here) have a dependency. You then specify whether you want setter or constructor injection. When Spring creates the Hibernate Object, it will attempt to also create a TransactionFactory and pass that to the Hibernate Object's setter. "Auto-wiring" them together for you.
    - Saish

Maybe you are looking for

  • Noise when scrolling!

    Trackpad, mouse, tablet, don't matter. Quiet but annoying buzzing sound, but not every time, when scrolling pages in safari or firefox. Brand new Macbook Pro 2.5 Any thoughts, suggestions?

  • Old versions of Photoshop

    Now that I have Photoshop CC do I need to keep the older versions of Photoshop on my computer. I have CS3 Extended, CS5 Update and the CS6 from when the subscription started. Bearing in mind that the CS3 qualifies me for the 12 months discount on my

  • Client-side programmatically submit???

    Hi! I need to make SelectOneChoice to submit ONLY when user press enter key (standard autosubmit is not acceptable as it submits each time user scrolls a list with cursor keys - which 99% users do!). So I need to "catch" enter keyPress with clientLis

  • "[item name]" can't be modified or deleted because it's required by OS X.

    OK, so I purchase ID3 Editor. • Download a .dmg file. • Open disk image: • Instructions tell me to copy software to Applications folder. Which I do. • Want to rename the Extras folder so that it reads "ID3 Extras", and shows up next to the App it ref

  • Oracle timezone conversion

    I have a requirment in which the database server time is being changed to GMT but one of the database users needs to store its data in CST or CDT as the case may be depending on daylight savings .I am thinking of writing a function which returns depe