Passing vector into class/methods

I am new to Vectors check this simple code out. I am trying to pass a vector onto another class then add an integer element to it. I see that its looking for an identifier but i dont unerstand how the code is for an identifier for a vector.
ERRORS: .\Remove.java:4: <identifier> expected
     public static void AddIntegers(varray);
^
.\Remove.java:4: ')' expected
     public static void AddIntegers(varray);
^
.\Remove.java:4: cannot resolve symbol
symbol : class varray
location: class Remove
     public static void AddIntegers(varray);
^
C:\Computer Work\Lab4\RemoveTest.java:11: cannot resolve symbol
symbol : method varray ()
location: class RemoveTest
          rm.AddIntegers(varray());
^
.\Remove.java:4: missing method body, or declare abstract
     public static void AddIntegers(varray);
^
.\Remove.java:6: cannot resolve symbol
symbol : variable varray
location: class Remove
          varray.AddElement(new Integer(13));
^
6 errors
Tool completed with exit code 1
import java.io.*;
import java.util.*;
public class RemoveTest
     public static void main(String[] args)
          Vector varray = new Vector();
          Remove rm = new Remove();
          rm.AddIntegers(varray);
          System.out.println(varray);
public class Remove
     public static void AddIntegers(varray);
          varray.AddElement(new Integer(13));

I think the question whether you should use Vector over arrays, but rather should you use Lists over arrays. Vectors are kind of deprecated. You should be using the Collections Framework as a whole, and that means that ordered items are in java.uti.Lists, where are a kind of java.util.Collection, and a Vector is just a particular kind of List, and not necessarily even the best kind -- an ArrayList or LinkedList is often better.
The advantage of arrays over Lists is that they can hold primitive types trivially. You can only hold objects in Lists, so you can put primitive class wrapper objects in Lists, but that has its disadvantages. Apparently in JDK 1.5 there's some syntactic sugar to make this easier, but there are still other disadvantages.
The advantages of Lists over arrays are like what you mentioned -- things like resizings are automatic, there are lots of convenience methods, etc. The Collections Framework provides an abstraction of, well, collections, which is a good thing over futzing with details like with arrays, frequently.

Similar Messages

  • Passing vectors into JSP from Servlet and passing data back to Servlet

    I have been building an MVC application.
    It has a controller which instantiates classes and evokes methods to
    populate vectors. These vectors are then passed into a JSP. This part of the application works fine.
    What I am having trouble with is a new JSP I have designed; this will
    display the data that is actioned by the FORM action. This is actioned
    based on the Search criteria entered by the user. Based on this a further vector is populated and brought back to the JSP as a vector
    and this is rendered via the TABLE tag. Again this works fine.
    Against each of the rows displayed, I have a print checkbox which can be checked by the user. On checking the records they want to print, they should then hint a Print button which should go back to the Servlet and print the data. THIS IS WHERE I HAVE THE PROBLEM. On going
    back to the servlet the checkbox values are not displayed, rather
    the values that initially populate the JSP. How do I get these new values back into the vector and hence accessible from the Servlet.
    Any help with be very much appreciated.
    Chris

    Thanks for this.
    Just to clarify I am not using Struts.
    What I am having difficulties with is the fact that:
    I can't get the checked values back to the Servlet - they keep the values they have in the bean - so as part of instantiating the bean class I set the value of the item to 'off'. The user will then check
    the checkbox which should presumbably set the value to 'on'. This isn't happening because the setter method of the bean is not evoked again
    because I don't come into this JSP again - the Servlet has finished here
    and now needs to print the records. It can't do this because as
    far as it is concerned nothing has changed since it last passed through
    the vector to the JSP.
    Even when I do the following:
    Enumeration paramNames = request.getParameterNames();
    String param = null;
    while (paramNames.hasMoreElements())
    param=(String)paramNames.nextElement();
    System.out.println("parameter " + param + " is " +
    request.getParameter(param));
    what comes back is the valus of 'off' as opposed to 'on'.
    The other thing is that 'request.getParameterNames()' only works
    with the first record in the vector, i.e. it doesn't fetch any other
    records that are rendered in the <TABLE> tag.
    In desperation is there anybody out there who can help me.
    Thanks
    Chris
    I am going to assume you are using a MVC framework
    like Struts or very similar (I am assuming that from
    the language you are using).
    When the servlet passes the vector back to the JSP
    page and you render the HTML that is passed back the
    client your Vector is gone. The Vector is not
    available at the HTML level that is being viewed at
    the browser.
    When the user selects the checkboxes and submits the
    page (by clicking the print button) the controller
    servlet (called ActionServlet in Struts, yours maybe
    called something else) forwards the request to the
    appropriate JavaBean and Servlet to process the
    request. Either the JavaBean has to recreate the
    Vector (not recommended) or the processing Servlet can
    (better). You can do this by recreating the Vector
    from scratch for the HttpRequest parameters or, at the
    time of the initial request, saving Vector to a
    session and then updating with the data you get back
    from the client (again from the HttpRequest
    parameters).
    Either way you have to work with
    HttpRequest.getParameter().

  • Trying to pass arguments into a method call and failing

    Hi everyone, I'm fairly new to programming, and newer to Java. I'm currently working on a project that pulls fields from a database based on a name, and I'm having some trouble getting the connection string set up.
    Statically defined, the database connects and the program logic that follows works just fine. The problem is that to future-proof this application, I need to pass the database URL, port, db instance, username, and password into the program as arguments from the batch file that will then be scheduled to run the program on a job-by-job basis.
    Product Version: NetBeans IDE 6.1 (Build 200805300101)
    Java: 1.6.0_06; Java HotSpot(TM) Client VM 10.0-b22
    System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
    Userdir: C:\Documents and Settings\xxxxxxxxxxx.SPROPANE\.netbeans\6.1
    Here's my current working source (with the network addresses obfuscated):
    package processsqrjob;
    import java.io.*;
    import java.sql.*;
    import java.util.Date;
    public class Main {
         * @param args jobname, jobparameters, HYPusername, HYPpassword, HYPservername, HYPport, oracleDBURL, oracleport (default 1512), SID (dbb?), oracleusername, oraclepass
         * @throws exeption
        // jobname [0], jobparams[1], hypusername [2], hyppassword [3], hypservername [4], hypport[5], oracledburl[6], oracleport[7], sid[8], oracleusername[9], oraclepass[10]
        public static void main(String[] args) throws SQLException
            DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@oracleserver.local.intranet.com:1521:dbname", "username", "pass");
            Statement stmt = con.createStatement();
            Date date = new Date(); //get the system date for output to both the error log and the DB's lastrun field
            System.out.println(date); //print the date out to the console
            System.out.println(args[0]); //print the job name to the console
            String sourcefolder=""; //we're going to load the job source folder into this variable based on the job's name
            String destfolder="";//same with this variable, except it's going to get the destination folder
            try {
                ResultSet rs = stmt.executeQuery("SELECT * FROM myschema.jobs WHERE NAME =\'"+args[0]+"\'");
                while ( rs.next() ) {
                    sourcefolder = rs.getString("sourcefolder");
                    destfolder = rs.getString("destfolder");
                stmt.executeQuery("UPDATE myschema.jobs SET lastrun ='"+date+"' WHERE name ='"+args[0]+"'");//put this after hyp code
    //            System.out.println(sourcefolder);
    //            System.out.println(destfolder);
    //            System.out.println(description);
                stmt.close(); //close up the socket to prevent leaks
            }catch(SQLException ex){
                System.err.println("SQLException: " + ex.getMessage());
                logError(args[0], ex.getMessage());
    }That works, and it connects to the database and everything. But when I pass the variables in from the project properties run settings, I get the following exception:
    Exception in thread "main" java.sql.SQLException: invalid arguments in call
            at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:111)
            at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:145)
            at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:207)
            at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:235)
            at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:440)
            at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:164)
            at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:34)
            at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:752)
            at java.sql.DriverManager.getConnection(DriverManager.java:582)
            at java.sql.DriverManager.getConnection(DriverManager.java:207)
            at processsqrjob.Main.main(Main.java:42)
    Java Result: 1That is with Connection con = DriverManager.getConnection("jdbc:oracle:thin:@oracleserver.local.intranet.com:1521:dbname", "username", "pass"); changed to Connection con = DriverManager.getConnection("jdbc:oracle:thin:@"+args[6]+":"+args[7]+":"+args[8]+"\", \""+args[9]+"\", \""+args[10]+"\"");{code}, with args 6 7 8 and 9 set to url, port, dbinstance, username, and password respectively.
    Perhaps it's the way I'm escaping the quotation marks, but I put that same line inside a System.out.println() and it output it exactly as I had typed it in statically before, so I don't know what it could be.
    I would really appreciate any advice. Thanks in advance for your time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I think you're mixing up SQL and Java. The Java method expects the user name and password as separate parameters, not encoded in one String. So you shouldn't be concatenating args[9] and args[10] at all, they should remain as separate parameters.
    The call should be:DriverManager.getConnection("jdbc:oracle:thin:@" + args[6] + ":"+ args[7] + ":" + args[8], args[9], args[10]);
                                                     parameter 1                                  2         3

  • Pass Table to Class Methods

    Hi.
    I want to pass the Standard and Hashed Table to Methods of CLass.
    Can anyone please provide a code snippet ?
    Currently it only has string as passed by value
    My Class code is :
    class ZCL_SHM definition
      public
      final
      create public .
    public section.
        data STRING_ATTR type STRING .
    Theses Statements does not work :
    data z_Table type any table.
    data z_Table type Hashed Table.

    You can't use generic types in the way you want to.  But there's a way round - pass references.  So in your class, you want an attribute to be a table that can be any kind of table and any structure.  What you do is instead have a class attribute my_table_ref TYPE REF TO DATA.
    Now you need to work out how to set the class attribute my_table_ref.  One way is to use a setter method, like SET_TABLE_REF, which has one importing parameter i_ref TYPE REF TO DATA.  Body is me->my_table_ref = i_ref.
    From the program using the class, assuming you've defined a table somewhere "t_my_table", you can set the attribute like this.
    DATA: io TYPE REF TO myclass.
    GET REFERENCE OF t_my_table INTO io->my_table_ref.
    When you want to access the table within the class, you dereference to a field-symbol in the method.
    FIELD-SYMBOLS: <my_table> TYPE ANY TABLE.
    ASSIGN my_table_ref->* TO <my_table>.
    You can then access <my_table> as you would any other dynamic table.
    ( Note - you can use generic table as IMPORTING and EXPORTING parameters of method.  Just not as attributes or RETURNING parameters - for those, you just need to pass the reference instead ).
    matt

  • Pass parameters into a method from other methods.

    I m testing  2 related applications with coded ui test and wanna pass a parameter from one method into another.
    how can i do that?
    Thank you in advance.

    Hi mah ta,
    Could you please tell us what about this problem now?
    If you have been solved the issue, would you mind sharing us the solution here? So it would be helpful for other members who get the same issue.
    If not, please let us know the latest information about it.
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Error while passing  parameter fot class method

    Hi abapers,
    i am trying to do alv grdi dispaly using class cl_gui_alv_grid. i am getting error "ITAB1" is not type-compatible with formal parameter 'IT_OUTTAB'.
    i attached code here.
    Internal Tables
    types: begin of itab,
          matnr type mara-matnr,
          maktx type makt-maktx,
          end of itab.
    data: itab1 like itab.
    DATA: alvgrid type ref to cl_gui_alv_grid.
    CALL METHOD ALVGRID->SET_TABLE_FOR_FIRST_DISPLAY
      EXPORTING
       I_BUFFER_ACTIVE               =
       I_BYPASSING_BUFFER            =
       I_CONSISTENCY_CHECK           =
        I_STRUCTURE_NAME              = 'ITAB'
       IS_VARIANT                    =
       I_SAVE                        =
       I_DEFAULT                     = 'X'
       IS_LAYOUT                     =
       IS_PRINT                      =
       IT_SPECIAL_GROUPS             =
       IT_TOOLBAR_EXCLUDING          =
       IT_HYPERLINK                  =
       IT_ALV_GRAPHICS               =
       IT_EXCEPT_QINFO               =
      CHANGING
        IT_OUTTAB                     = itab1.
       IT_FIELDCATALOG               =
       IT_SORT                       =
       IT_FILTER                     =
    EXCEPTIONS
       INVALID_PARAMETER_COMBINATION = 1
       PROGRAM_ERROR                 = 2
       TOO_MANY_LINES                = 3
       others                        = 4
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
               WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    please help me.

    Try this -
    CALL METHOD ALVGRID->SET_TABLE_FOR_FIRST_DISPLAY
    EXPORTING
    I_BUFFER_ACTIVE =
    I_BYPASSING_BUFFER =
    I_CONSISTENCY_CHECK =
    I_STRUCTURE_NAME = 'ITAB'
    IS_VARIANT =
    I_SAVE =
    I_DEFAULT = 'X'
    IS_LAYOUT =
    IS_PRINT =
    IT_SPECIAL_GROUPS =
    IT_TOOLBAR_EXCLUDING =
    IT_HYPERLINK =
    IT_ALV_GRAPHICS =
    IT_EXCEPT_QINFO =
    CHANGING
    IT_OUTTAB = <b>itab1[].</b>
    IT_FIELDCATALOG =
    IT_SORT =
    IT_FILTER =
    EXCEPTIONS
    INVALID_PARAMETER_COMBINATION = 1
    PROGRAM_ERROR = 2
    TOO_MANY_LINES = 3
    others = 4
    Cheers

  • Passing T into a method

    I did these methods twice, and I'd like to change the signature to something like:
    private void removeAllArticles(<T>)
    Is that possible, and, what's the terminology?
    public class DatabaseOps {
        private EntityManagerFactory factory = Persistence.createEntityManagerFactory("AssignmentPU");
        private static Logger logger = Logger.getLogger(DatabaseOps.class.getName());
        private void removeAllArticles() {
            logger.log(Level.INFO, "emptying table");
            EntityManager em = factory.createEntityManager();
            Query query = em.createNativeQuery("select * from article", Article.class);
            @SuppressWarnings("unchecked")
            List<Article> articles = query.getResultList();
            em.getTransaction().begin();
            for (Article article : articles) {
                logger.log(Level.INFO, "removing\n" + article);
                em.remove(article);
            em.getTransaction().commit();
            em.close();
        private void removeAllFeeds() {
            logger.log(Level.INFO, "emptying table");
            EntityManager em = factory.createEntityManager();
            Query query = em.createNativeQuery("select * from feed", Feed.class);
            @SuppressWarnings("unchecked")
            List<Feed> feeds = query.getResultList();
            em.getTransaction().begin();
            for (Feed feed : feeds) {
                logger.log(Level.INFO, "removing\n" + feed);
                em.remove(feed);
            em.getTransaction().commit();
            em.close();
         //other methods ommitted
    }thanks,
    Thufir

    I'm not familiar with the classes you're using, so I can't test it.
    Do you mean something like this?
    public class DatabaseOps {
        public static final class MyTableNames {
         private static final HashMap<Class<? extends SomeInterface>, String> classMap;
         static {
             classMap = new HashMap<Class<? extends SomeInterface>, String>();
             classMap.put(Feed.class, "feed");
             classMap.put(Article.class, "article");
         public static <T extends SomeInterface> String getTableName(Class<T> cls) {
             return classMap.get(cls);
        public static interface SomeInterface {
        private EntityManagerFactory factory = Persistence
             .createEntityManagerFactory("AssignmentPU");
        private static Logger logger = Logger
             .getLogger(DatabaseOps.class.getName());
        private <T extends SomeInterface> void removeAll(Class<T> cls) {
         String tableName = MyTableNames.getTableName(cls);
         if (tableName == null) {
             throw new IllegalArgumentException(cls.getName()
                  + " is not a valid class for this function");
         } else {
             logger.log(Level.INFO, "emptying table");
             EntityManager em = factory.createEntityManager();
             Query query = em.createNativeQuery("select * from " + tableName,
                  cls); //
             @SuppressWarnings("unchecked")
             List<T> feeds = query.getResultList();
             em.getTransaction().begin();
             for (T feed : feeds) {
              logger.log(Level.INFO, "removing\n" + feed);
              em.remove(feed);
             em.getTransaction().commit();
             em.close();
        // other methods ommitted
    }Piet

  • How do u pass an object into a method

    I want to create a method getData that takes an object of type Helper and returns an object of the same type.
    how do u pass objects into a method and how do u get objects as returns im a bit confused

    That will just allow you to pass a parameter. If you want to return a helper object
    Helper paramHelper = new Helper();
    Helper someHelper = callMethod(paramHelper);
    public Helper callMethod(Helper hobj) {
        //<some code>
        Helper retHelper = new Helper();
        //<blah, blah>
        return retHelper;

  • JRC with JavaBeans datasrc - how to pass params into javabean.getResultSet?

    Hi.
    I'm developing javabeans data sources for crystal reports for the java/JRC engine.  I've seen the document entitled Javabeans Connectivity for Crystal.  It TALKS ABOUT passing params into the methods that return java.sql.ResultSets but there is absolutely no example code anywhere that I can find on how to do it.
    What I don't understand is:  Since the JRC engine is basically controlling the instantiation of the javabean, other than calling some type of fetch method in the constructor, how the heck am I supposed to pass in db connection info and a sql string? 
    Anybody got sample code for how to call/where to call parameters that I would put in a custom getResultSet method??
    Thanks.

    I don't think that a Connection Pool class would be an ideal candidate for becoming a JavaBean. One of the most prevalent use of a JavaBean class it to use it as a data object to collect data from your presentation layer (viz. HTML form) and transfer it to your business layer. If the request parameter names match the Bean's property names, a bean can automatically get these values and initialize itself even though it has a zero argument ctor. Then a Bean could call methods in the business layer to do some processing, to persist itself etc.

  • Passing vectors or whatever

    writing video store applet for school.
    applet is main menu only, create frames for other duties(i.e. add a new customer...etc.)try to pass vectors to other frames from applet but get null pointer exception when I try to load vector with object.
    any ideas.
    thanks

    here is a pert of the code, I tried to highlight the problem spots
    import javax.swing.*;
    import javax.swing.JApplet.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.Font;
    public class videoApp extends JApplet implements SwingConstants{
         private JFrame newVideo,newCustomer,newRental;
         private Vector customerList,videoList,rentaList;
         private addCustomer newCust;
         private addVideo newVid;
         //,newVideoPanel;
         private JButton transaction = new JButton("Video Rental");
         private JButton addCust = new JButton("New Customer");
         private JButton addVideo = new JButton("New Video");
         private JButton listVideo_customer = new JButton("Videos/Customer History");
         private JButton listCustomer_video = new JButton("Customer/Video History");
         public void init(){
              Container appPane = getContentPane();
              appPane.setLayout (new FlowLayout ());
              appPane.add(transaction);
              appPane.add(addCust);
              appPane.add(addVideo);
              appPane.add(listVideo_customer);
              appPane.add(listCustomer_video);
              pass vector to class
         --->newCust = new addCustomer();//(customerList);<---
              newVid = new addVideo();
              addCust.addActionListener(new ActionListener () {
                                  public void actionPerformed (ActionEvent event) {
                                  newCust.show();
    }//ends videoApp
    import javax.swing.*;
    import javax.swing.JApplet.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.Font;
    //should extend JPanel instead creat frame in videoApp add addcustomer?
    class addCustomer extends JFrame implements SwingConstants{
    private String tmpName,tmpAddress,tmpPhone,tmpId;
    private static int i = 100;//for id
    private Customer cust;
    private Vector custList = new Vector();
    private int width;
    private int height;
    JLabel header = new JLabel ("Add A Customer");
    JLabel name = new JLabel ("Name");
    JTextField nameTxt = new JTextField("",20);
    JLabel address = new JLabel ("Address");
    JTextField addressTxt = new JTextField("",20);
    JLabel phone = new JLabel ("Phone");
    JTextField phoneTxt = new JTextField("",20);
    JLabel id = new JLabel ("Id");
    JTextField idTxt = new JTextField("",20);
    JButton addButton = new JButton("Add Customer");
    JButton exitButton = new JButton("Close");
    public addCustomer(){//(Vector v){
              *****receives vector from applet
              custList = v;
              Toolkit tk = Toolkit.getDefaultToolkit();
              Dimension size = tk.getScreenSize();
              width = size.width;
              height = size.height;
              setSize(width/2,height/2);
              setLocation(width /4, height / 4);
              setTitle("New Customer");
              Image img = tk.getImage("tv.gif");
              setIconImage(img);
              Container contentPane = getContentPane ();
              GridBagLayout custLayout = new GridBagLayout();
              contentPane.setLayout(custLayout);
              GridBagConstraints custConstraints = new GridBagConstraints();
              setConstraints(custConstraints,0, 0, 2, 1);
              custConstraints.insets.bottom = 10;
              header.setFont(new Font("Arial", Font.ITALIC, 24));
              contentPane.add(header,custConstraints);
              custConstraints.insets.bottom = 2;
              setConstraints(custConstraints,0,1, 1, 1);
              contentPane.add(name,custConstraints);
              setConstraints(custConstraints,1, 1, 1, 1);
              contentPane.add(nameTxt,custConstraints);
              setConstraints(custConstraints,0,2, 1, 1);
              contentPane.add(address,custConstraints);
              setConstraints(custConstraints,1,2, 2, 1);
              contentPane.add(addressTxt,custConstraints);
              setConstraints(custConstraints,0,3, 1, 1);
              contentPane.add(phone,custConstraints);
              setConstraints(custConstraints,1,3, 2, 1);
              contentPane.add(phoneTxt,custConstraints);
              setConstraints(custConstraints,0,4, 1, 1);
              contentPane.add(id,custConstraints);
              custConstraints.insets.bottom = 10;
              setConstraints(custConstraints,1,4, 2, 1);
              idTxt.setEditable(false);
              idTxt.setBackground(Color.white);
              contentPane.add(idTxt,custConstraints);
              //custConstraints.insets.right = 50;
         setConstraints(custConstraints,0,5, 1, 1);
              contentPane.add(addButton,custConstraints);
              //custConstraints.insets.right = 0;
         setConstraints(custConstraints,1,5, 1, 1);
              contentPane.add(exitButton,custConstraints);
              exitButton.addActionListener(new ActionListener () {
                        public void actionPerformed (ActionEvent event) {
                        setVisible(false);
              addButton.addActionListener(new ActionListener () {
                   public void actionPerformed (ActionEvent event) {
                        tmpId = createId();
                        idTxt.setText(tmpId);
                        cust = new Customer(nameTxt.getText(),addressTxt.getText(),phoneTxt.getText(),tmpId);
                        System.out.println("Name: "+cust.getName()+" Address: "+ cust.getAddress()+" Phone: "+ cust.getPhone()+" Id: "+ cust.getId());
                        ****null pointer exception***
                        custList.addElement(cust);
                        //System.out.println("Name: "+ nameTxt.getText());
                        //System.out.println("Name: "+ cust.getName() +" Address: "+ cust.getAddress()+" Phone: "+ cust.getPhone()+" Id: "+ cust.getId());
    /*exitButton.addActionListener(new ActionListener () {
                                  public void actionPerformed (ActionEvent event) {
                                  Enumeration customerList = custList.elements();
                                  while(customerList.hasMoreElements())
                                       cust= (Customer)customerList.nextElement();
                                       System.out.println("Name: "+cust.getName()+" Address: "+ cust.getAddress()+" Phone: "+ cust.getPhone()+" Id: "+ cust.getId());
         private void setConstraints(GridBagConstraints component,int x, int y, int w, int h) {
         component.gridx = x;
         component.gridy = y;
         component.gridwidth = w;
         component.gridheight = h;
         private static String createId()
              String id;
              id = "C" + i ;
              i++;
              return id;
    }//ends addCustomer

  • How to call a java method so I can pass a file into the method

    I want to pass a file into a java method method from the main method. Can anyone give me some help as to how I pass the file into the method - do I pass the file name ? are there any special points I need to put in the methods signature etc ?
    FileReader file = new FileReader("Scores");
    BufferedReader infile = new BufferedReader(file);
    Where am I supposed to put the above text - in the main method or the one I want to pass the file into to?
    Thanks

    It's a matter of personal preference really. I would encapsulate all of the file-parsing logic in a separate class that implements an interface so that if in the future you want to start taking the integers from another source, e.g. a db, you wouldn't need to drastically alter your main application code. Probably something like this, (with an assumption that the numbers are delimited by a comma and a realisation that my file-handling routine sucks):
    public class MyApp{
    public static void main(String[] args){
    IntegerGather g = new FileIntegerGatherer();
    Integer[] result = g.getIntegers(args[0]);
    public interface IntegerGatherer{
    public Integer[] getIntegers(String location);
    import java.io.*;
    public class FileIntegerGatherer implements IntegerGatherer{
    public Integer[] getIntegers(String location){
    FileInputStream fs=null;
    try{
    File f = new File(location);
    fs = new FileInputStream(f);
    byte[] in = new byte[1024];
    StringBuffer sb = new StringBuffer();
    while((fs.read(in))!=-1){
    sb.append(new String(in));
    StringTokenizer st = new StringTokenizer(sb.toString(),",");
    Integer[] result = new Integer[st.countTokens()];
    int count = 0;
    while(st.hasMoreTokens()){
    result[count]=Integer.valueOf(st.nextToken());
    count++;
    catch(IOException e){
    //something sensible here
    finally{
    if(fs!=null){
    try{
    fs.close();
    catch(IOException f){
    return result;
    Once compiled you could invoke it as java MyApp c:\myInts.txt
    Sorry if there are typos in there, I don't have an ide open ;->

  • Passing select-options table to a class method

    Hi,
    I have to pass a table which contains a select-options to a class method as a param...
    How I do this??
    DATA s_mail TYPE  z_mail_rng.
    o_mail->add_receiver( ? ).
    (add_receiver's formal param is TYPE ANY)
    Plese give me help.
    Thanks.

    Hi,
    I send coding for  how to use select-options in class.
    May it is useful for u
    tables:marc.
    selection-screen begin of block b1 with frame title text-001.
    select-options: s_matnr for marc-matnr.
    selection-screen end of block b1.
    class c3 definition.
    public section.
    types: begin of ty_marc,
    matnr type marc-matnr,
    werks type marc-werks,
    end of ty_marc.
    data: wa_itab type ty_marc.
    data: itab type table of ty_marc .
    data: wa_matnr type r_matnr.
    methods: add.
    private section.
    *methods: sub.
    endclass.
    class c3 implementation.
    method add .
    select matnr
    werks
    from marc into table itab where matnr IN s_matnr.
    write:/ 'material no', 20 'plant'.
    loop at itab into wa_itab.
    write:/ wa_itab-matnr,
    wa_itab-werks.
    endloop.
    endmethod .
    endclass.
    start-of-selection.
    data b1 type ref to c3.
    create object b1 .
    call method b1->add.

  • Passing Vectors to Methods

    import java.util.*;
    public class usingVectors
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)
              int VECTOR_SIZE;
              System.out.print("Enter the size of the array: ");
              VECTOR_SIZE = console.nextInt();
              System.out.println();
    Vector<Integer> listA = new Vector<Integer>();
    System.out.print("Enter " + VECTOR_SIZE + " integers: ");
    fillArray(listA, VECTOR_SIZE);
    System.out.println();
    System.out.print("List of Integers that you inputted: \n ");
    printArray(listA, VECTOR_SIZE);
    System.out.println();
    System.out.println("The position of the smallest integers in the array is: " + indexSmallest(listA, VECTOR_SIZE));
    System.out.println("The smallest integer in the array is: " + listA[indexSmallest(listA, VECTOR_SIZE)]);
    public static void fillArray(int list, int sizeOfVector)
    int index;
    for (index = 0; index < sizeOfVector; index++)
    list[index] = console.nextInt();
         public static void printArray(int list, int sizeOfVector)
              int index;
              for (index = 0; index < sizeOfVector; index++)
              System.out.print(list[index] + " ");
         public static int indexSmallest(int list, int sizeOfVector)
              int index;
              int smallIndex = 0;
              for (index = 0; index < sizeOfVector; index++)
              if (list[smallIndex] > list[index])
         smallIndex = index;
              return smallIndex;
    Im trying to pass a vector to a method. Im not sure what i am doing wrong if anyone could look at what im doing wrong i would appreciate it.
    ER:usingVectors.java:19: fillArray(int,int) in usingVectors cannot be applied to (java.util.Vector<java.lang.Integer>,int)
    fillArray(listA, VECTOR_SIZE);

    My first problem was to write a method, smallestIndex that takes as its parameters an int array and its size. Return the smalles element in the array and its postion. Now i have that done and it was good. He wants us to change that program to use vectors. So i feel like i have done most of it right but like you said the error. It won't pass the vector through to the method. I believe
    ok thank you. I guess what i should ask you now. In my line of code. How do i set the parameters to pass a Vector instead of the int?
    THANK YOU FOR YOU HELP
    Vector<Integer> listA = new Vector<Integer>();                     
            System.out.print("Enter " + VECTOR_SIZE + " integers: ");                       
            fillArray(listA, VECTOR_SIZE);  **This is where i call my method with the vector name listA, and the int VECTOR_SIZE, it pops the problem here or would it be in the declaring the new varibles at the start of the method**                      
            System.out.println();                                  
            System.out.print("List of Integers that you inputted: \n     ");                       
            printArray(listA, VECTOR_SIZE);                       
            System.out.println();                                        
            System.out.println("The position of the smallest integers in the array is: " + indexSmallest(listA, VECTOR_SIZE));  
            System.out.println("The smallest integer in the array is: " + listA[indexSmallest(listA, VECTOR_SIZE)]);
        public static void fillArray(int list, int sizeOfVector) *Or would it be here?*
            int index;
            for (index = 0; index < sizeOfVector; index++)
                list[index] = console.nextInt();
        }

  • In webdynpro ,Passing field symbols as values to class methods

    Hi
    Please tell me the ways of accessing database in webdynpro abap(not directly). I am calling Class method for accessing database. As currently I am directly accessing database in my webdynpro application. I have created a class and method for the same.
    In my method I want to use select statement which will return table with values to webdynpro application. So for select statement(Calling Method) I need to use my field symbol values as where in clause .
    Could anyone please help with example code?
    Thanks,
    Ujjwal

    data: in_line type ref to data.
    CREATE DATA in_line LIKE LINE OF <dyn_tab>.
      ASSIGN in_line->* TO <dyn_wa>.
    You can create a data reference and assign it to a field symbol and change the values. direclty passing field symbols is not possible.
    Abhi

  • Passing select-options to class methods

    Hi,
    I want to pass a select-option filled in the selection screen by the user to a method of my class. Since select-options are hold as an internal table with fields sign option low high, and passing internal tables to methods require typing, what should I write as the name of this internal table type?
    For example;
    select-options: so_carid for spfli-carrid.
    I want to pass the contents of so_carid to my method defined in a class

    hI
    Triggering and Handling events
    At the moment of implementation, a class defines its:
             Instance events (using the EVENTS statement)
            Static events (using the CLASS-EVENTS statement)
    Classes or their instances that receive a message when an event is triggered at runtime and want to react to this event define event handler methods. Statement: METHODS
    CLASS IC1_VEICHLE DEFINATION.
    PUBLIC SECTION.
    METHOD CONSTRUCTOR IMPORTING
    EVENTS VEICHEL_CREATION.
    ENDCLASS
    CLASS LC1_VEICHLE IMPLIMENTATION.
    METHOD CONSTRUCTOR
    RAISE EVENT VEICHLE_CREATION.
    REWARD IF USEFULL

Maybe you are looking for

  • ERROR IN DOWNLOADING FILE

    hi guru's,     I am facing a problem in calling gui_download function it creates a file but not download the content of file in it. the code is DATA : BEGIN OF T_SOLI OCCURS 0,           LINE(255) TYPE C,        END OF T_SOLI. T_SOLI-LINE = 'HAHAHJSH

  • "Unkown Error (-50)" when trying to change iPod settings via iTunes

    Hello everyone. I got an 5.5 iPod Video (30gb) for christmas and I can't update the name of the Ipod nor change the settings for music, TV shows, movies, podcasts, pictures or even reset it! I can however sync music, tv shows, movies and pocasts (not

  • Time zone in message monitoring (GMT)

    Hi all - as I understand, all messages in XI are saved with timestamps within GMT time zone. This results in having a possible mismatch between displays in Adapter Engine (e.g., message monitoring) and Integration Engine (e.g., SXMB_MONI), the letter

  • How to create application/ application link

    Hi All, Since I have raised several queries you all know that I am doing my project on purchasing and inventory system based on oracle. As a part of this project I have creates number of forms (including Login and Menu form) merely I have just saved

  • Quicktime Thumbnail missing after publishing

    I'm using iWeb '09 3.0.1. to build my website. I've got lots of quicktime videos. I used the Inspector to select a thumbnail for my Quicktime clips, but after publishing the clips just start in black. I've had this problem since I first built the sit