Passing an array to a method

This is probably a really simple question - but I'm new to java!
Object (is that the right word?) Car consists of some information about a car - registration number, engine size etc.
I have defined an array of objects of type car, and I want to pass the whole thing to a method.
Specifically...
I want to pass an inputted search term - the registration number, to a search method to return the number of the element of the array in which that record is stored. Presumably I need to pass the whole array?
I think what might be causing the problem is the definition of the method:
private int searchCar(String regNumber, int records, Car carArray[]Also, I don't know how to refer to regNumber as stored in carArray. I'm guessing it's carArray[number].regNumber or something like that.
Do I need to initialise the whole array before I use it?
Thanks for any help - I'm clueless!

You should provide in your class Car ,methods to get (and set if necessary) each of the instance variables associated with a Car object. For example your car class should look something like this:
public class Car
private String make, model, colour, regNumber;
public Car(String a, String b, String c, String d)
make = a;
model =b;
colour = c;
regNumber = d;
public String getModel()
return model;
public String getMake()
{ return make;
public string getColour()
return colour;
public string getRegNumber()
return regNumber;
public string to String()
return getMake() + " " + getModel() + " " + getColour() + " " + getRegNumber;
}in your main method
// create your Array of Car objects and the mthod as below.
public int searchCar(Car [ ] cars, String reg)
int found =-1;
for (int counter = 0; counter < cars.length;  ++ counter)
if (cars[counter].getRegNumber.equals(reg))
found = counter;
break;
return found;
}// end searchCarCall this method with something like:
int index = carSearch(carArray, "SM51 KJL");
if(index != -1)
System.out.println("This full details of the requested car are : " + carArray[index].toString());
else
System.out.println("This car has not been recorded on our System");
Haven't compiled this so aplogies for any typing errors.

Similar Messages

  • How do I pass an array to a method?

    Hopefully you guys don't mind answering one of my stupid questions :o(
    I have problem passing an array to a method.
    //Here is the code that calls to the method:
    String[] Folder = new String[19];
    int cnt;
    for(cnt=0; cnt<20; cnt++){
    Folder[cnt] = request.getParameter("searchfolder_name" + (cnt + 1));
    ProcessNotify(Folder[cnt]);
    //================================================================
    //Here the the method that is supposed to take in the array
    private void ProcessNotify(String FolderName[]){
    FolderName = new String[19];
    int cnt;
    for(cnt=0; cnt<20; cnt++){
    System.out.println("Folder Name: " + FolderName[cnt]);
    I got an error that says java.lang.String[] can not be applied to java.lang.String
    I thought "String FolderName[]" is an array? Anyway... I'm confused. If you know the answer, plz let me know :o) big thx
    lil

    ProcessNotify(Folder[cnt]);
    Are you trying to pass the whole array or just one piece from it? What you coded, tried to pass just one piece by specifying a subscript. BTW variable cnt is a subscript out of range.
    If you meant to pass the whole array, just use it's name with no subscript.

  • Passing an array to a method taking an Object?

    Hi,
    I need to pass an array of randomly generated numbers to a method that takes an Object.
    I can't seem to figure out how to do this...
    Here is my code for creating the array of random numbers:
    Random generator = new Random();
    for (int i = 0; i < size; i++)
    a[ i ] = generator.nextInt();
    mySort(a);
    Here is the signature of the method I am trying to pass it to:
    public static void mySort(Comparable [] a)
    When I compile I get the following message: mySort ( java.lang.Comparable[] ) cannot be applied to (int[]) mySort(a);
    How can I convert the array into an Object?
    Any help is much appreciated!

    >
    It'll be easier in java 1.5...But will result in terrible code being written by folks who don't understand the penalties incurred with auto-boxing.
    If you have to sort an array of integers, grab a QuickSort implementation that works with int[] directly (there is one built into the Arrays class) - creating all of those temporary objects kills performance.
    - K

  • Passing an array from one method to another

    I am passing an array from my "load" method and passing it to be displayed in my "display" method in an applet .
    I made the array a class variable (to be able to pass it to the "display" method).
    The applet runs, but nothing seems to be in the array.The screen says applet started, but nothing else. There does not seem to be any CPU activity.
    Trying to debug this, I have tried to paint the screen during the array build. I never figured out how to do this. So I made this a non applet class, put it in debug, and the array seems to load okay.
    Any help is appreciated.
    This is the applet code:
    import java.applet.Applet;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    public class urla extends java.applet.Applet
    int par1;
    int i = 1;
    int j = 20;
    int m = 0;
    int k = 0;
    String arr[] = new String[1000];
    String inputLine;
        public void load() throws Exception
          try
            URL mysite = new URL("http://www.xxxxxxxxxxxxxx.html");
           URLConnection ms = mysite.openConnection();
           BufferedReader in = new BufferedReader(
           new InputStreamReader(
           ms.getInputStream()));
             while ((inputLine = in.readLine()) != null)
               arr[m] = inputLine;
               m++;
           in.close();
          catch (MalformedURLException e)
            k++;
        public void display(Graphics screen)
          screen.drawString("THE FOLLOWING HAVE ADDED THEIR BIOS:",5 ,5);
          for (int i = 0; i < 20; i++);
            j = j + 20;
            screen.drawString("output - "
            + arr, 5, j);
            repaint() ;
    }

    String arr[] = new String[1000];is this typing mistake????? because if u did it in
    program as well i don think it will work.. the tag is
    innnside array lenght... hope iam saying this right!!no, he had the bold form tags (b and /b inside square brackets) in his previous non-code tagged post. He carried it over to this post and they caused an error. I highly doubt that they were in his actual program. Just delete them.
    Message was edited by:
    petes1234

  • Passing the array into actionPerformed method

    Hi friends! I am new at java. I made a tictactoe game board with GUI and it is designed according to nxn (desired any n value). When I pressed to any button, it should write an X to my board but I could not passed the button's action. My problem is that my actionPerformed method does not accept array button[j]. In the below there is a part of my code :
    for(int j=0;j<button.length;j++)     // adding the buttons
    button[j].addActionListener(this);
    public void actionPerformed(ActonEvent evt)
    // what can I read here for detecting the right button? button length is changable, it is depent on what we desire at first.
    // I tried this code in this area but it does not work:
    // if (evt.getSource()==button[j])
    // button[j].setText("X");
    // normally, it works if I write every button individually like that:
    // button1.addActionListener(this); (same for other buttons)
    // public void actionPerformed (ActionPerformed evt)
    // if (evt.getSource()==button1)
    // button1.setText("X"); (same code for other buttons)
    // but I want to make a generalized board action
    }I will be appreciated with your helps...
    Musty

    Hi musty4284,
    The getSource method of ActionEvent(not ActonEvent) returns an object and the way you're comparing objects is wrong.
    Theorically, you should do something like this :
    public void actionPerformed(ActionEvent evt) {
        JButton b = (JButton) evt.getSource();
        if ( button[j].equals(b) ) {
    }Edit :
    When using a listener for an array of JButton, it is a good idea to give a unique identifier to each button (for example, their index in the array). The JButton class has a setName method not to confuse with the setText method.
    While building your array of JButton, you can do :
    JButton[] button = new JButton[9];
    for (int i = 0; i < 9; i++) {
        button[i] = new JButton();
        button.setName(i);
    While handling the event :public void actionPerformed(ActionEvent evt) {
    JButton b = (JButton) evt.getSource();
    int index = Integer.parseInt(b.getName());
    button[index].setText("X");
    Edited by: Chicon on Oct 4, 2009 11:20 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Help needed with passing an array to a method

    here is a small class i'm working on. it's supposed to take each address on an array, and check it for an iis machine, then check a couple of known malformed urls to see if the machine has been patched. my problem is that i can't get the method that does the probing to accept input from the array. it won't even compile, and i'm sure my problem's pretty simple, it's just that i don't quite have afull grasp on java yet. btw, the get/set methods are mandatory, as my instructor refuses to even look at code without them.
    import java.net.*;
    import java.io.*;
    public class PortProbe
         * attribute(s)
         private String[] addressesToBeScanned;
         * accessor methods
         public String[] getAddressesToBeScanned()
              return addressesToBeScanned;
         public void setAddressesToBeScanned(String[] addressesToBeScanned)
              this.addressesToBeScanned = addressesToBeScanned;
         public String getAddressesToBeScanned(int index)
              return addressesToBeScanned[index];
         public void setAddressesToBeScanned(int index, String value)
              addressesToBeScanned[index] = value;
         * helping method to determine the software running on the server
         public void probe80()
              URL myurl = null;
    URLConnection urlConnection = null;
              try
                   myurl = new URL(getAddressesToBeScanned());
              catch (MalformedURLException mal)
                   System.out.println("Exception caught: " + mal);
              try
                   urlConnection = myurl.openConnection();
    catch (IOException ioe)
                   System.out.println("Exception caught: " + ioe);
              System.out.println(urlConnection.getURL());
              System.out.println(urlConnection.getHeaderField("Server"));
         * constructor method(s)
         public PortProbe() //this constructor will initialize each array element individually
              setAddressesToBeScanned(new String[3]);
              setAddressesToBeScanned(0, "http://216.18.80.142/scripts/..%255c..%255c..%255c..%255cwinnt/system32/cmd.exe?/c+dir");
              setAddressesToBeScanned(1, "http://216.18.84.152/scripts/..%255c..%255c..%255c..%255cwinnt/system32/cmd.exe?/c+dir");
              setAddressesToBeScanned(2, "http://216.18.84.161/scripts/..%255c..%255c..%255c..%255cwinnt/system32/cmd.exe?/c+dir");
         * main method
         public static void main(String[] args)
              PortProbe myProbe = new PortProbe();
              for (int i = 0; i < myProbe.addressesToBeScanned.length; i++)
                   myProbe.probe80();
                   i++;
    that's it. can anyone help me out.
    thanks

    thank you all for your responses. the program now compiles and runs successfully. but the results i'm getting aren't the same as what i'm expecting.
    here is the revised code that compiles and runs:
    import java.net.*;
    import java.io.*;
    public class PortProbe
         * attribute(s)
         private String[] addressesToBeScanned;
         * accessor methods
         public String[] getAddressesToBeScanned()
              return addressesToBeScanned;
         public void setAddressesToBeScanned(String[] addressesToBeScanned)
              this.addressesToBeScanned = addressesToBeScanned;
         public String getAddressesToBeScanned(int index)
              return addressesToBeScanned[index];
         public void setAddressesToBeScanned(int index, String value)
              addressesToBeScanned[index] = value;
         * helping method to determine the software running on the server
         public void probe80()
              URL myurl = null;
    URLConnection urlConnection = null;
              try
                   for (int i = 0; i < getAddressesToBeScanned().length; i++)
                        myurl = new URL(getAddressesToBeScanned());
              catch (MalformedURLException mal)
                   System.out.println("Exception caught: " + mal);
              try
                   urlConnection = myurl.openConnection();
    catch (IOException ioe)
                   System.out.println("Exception caught: " + ioe);
              System.out.println(urlConnection.getURL());
              System.out.println(urlConnection.getHeaderField("Server"));
         * constructor method(s)
         public PortProbe() //this constructor will initialize each array element individually
              setAddressesToBeScanned(new String[3]);
              setAddressesToBeScanned(0, "http://216.18.80.142");
              setAddressesToBeScanned(1, "http://137.113.192.101");
              setAddressesToBeScanned(2, "http://216.18.84.161");
         * main method
         public static void main(String[] args)
              PortProbe myProbe = new PortProbe();
              for (int i = 0; i < myProbe.addressesToBeScanned.length; i++)
                   myProbe.probe80();
                   i++;
    please pardon the formatting. there is a constructor that sets the elements in the array. but when i execute the program, this is the output i get:
    http://216.18.84.161
    null
    http://216.18.84.161
    null
    there is nothing else. and it appears that only one of the elements is being called. i don't know where the nulls are coming from. what the program should do (and did do fine before i started with the arrays) is determine the server software running on the machine being probed. there's got to be a mistake in my logic here somewhere, but i'm not experienced enough yet to find where it is.
    thanks again.

  • Passing Array to Another Method

    Hello, I created a program with an array in one of the methods. I have been trying to figure out how to correctly pass the array to another method in the same class. I know my problem is in my method delcaration statements. Could someone please show me what I am doing wrong? Please let me know if you have any questions. Thanks for your help.
    import javax.swing.*;
    import java.util.*;
    class Bank1 {
         public static void main(String[] args) {
              Bank1 bank = new Bank1();
              bank.menu();
         //Main Menu that initializes other methods
         public void menu( ) {
              Scanner scanner = new Scanner(System.in);
              System.out.println("Welcome to the bank.  Please choose from the following options:");
              System.out.println("O - Open new account");
              System.out.println("T - Perform transaction on an account");
              System.out.println("Q - Quit program");
              String initial = scanner.next();
              char uInitial = initial.toUpperCase().charAt(0);
              while (uInitial != 'O' && uInitial != 'T' && uInitial != 'Q') {
                   System.out.println("That was an invalid input. Please try again.");
                   System.out.println();
                   initial = scanner.next();
                   uInitial = initial.toUpperCase().charAt(0);
              if (uInitial == 'O') newAccount();
              if (uInitial == 'T') transaction();
         //Method that creates new bank account
         public Person[] newAccount( ) {
              Person[] userData = new Person[1];
              for (int i = 0; i < userData.length; i++) {
                   Scanner scanner1 = new Scanner(System.in);
                   System.out.println("Enter your first and last name:");
                   String name = scanner1.next();
                   Scanner scanner2 = new Scanner(System.in);
                   System.out.println("Enter your address:");
                   String address = scanner2.next();
                   Scanner scanner3 = new Scanner(System.in);
                   System.out.println("Enter your telephone number:");
                   int telephone = scanner3.nextInt();
                   Scanner scanner4 = new Scanner(System.in);
                   System.out.println("Enter an initial balance:");
                   int balance = scanner4.nextInt();
                   int account = i + 578;
                   userData[i] = new Person( );
                   userData.setName               ( name );
                   userData[i].setAddress          ( address );
                   userData[i].setTelephone     ( telephone );
                   userData[i].setBalance          ( balance     );
                   userData[i].setAccount          ( account     );
                   System.out.println();
                   System.out.println("Your bank account number is: " + userData[i].getAccount());
              return userData;
              menu();
         //Method that gives transaction options
         public void transaction(Person userData[] ) {
              System.out.println(userData[0].getBalance());

    Thank you jverd, I was able to get that to work for me.
    I have another basic question about arrarys now. In all of the arrary examples I have seen, the array is populated all at once using a for statement like in my program.
    userData = new Person[50];
    for (int i = 0; i < userData.length; i++) In my program though, I want it to only fill the first array parameter and then go up to the main menu. If the user chooses to add another account, the next spot in the array will be used. Can someone point me in the right direction for doing this?

  • Passing an array of integers to a method...

    here's the case, i have 2 array of integers parent and child. how can i pass the arrays in a method so i can evaluate the contents of both arrays?
    here's the block of the code that contains what i'm talking about.
    for(int i=0; i<tree.length; i++) {//separate child from parent      
         int[] parent = new int[(tree.length()/2)];
         int[] child = new int[(tree[i].length()/2)];
         for(int j=0, ctr=0; j<tree[i].length(); j++, ctr++) {               
              parent[ctr] = Integer.parseInt(Character.toString(tree[i].charAt(j))); //get the parents
              j++;
              child[ctr] = Integer.parseInt(Character.toString(tree[i].charAt(j))); //get the children
         if(isTree(parent, child)) //evaluate if case is a tree
         System.out.println("Is a tree");
         else
         System.out.println("Is not a tree");
    }//separate child fronm parent     

    geez, thanks... adding "static" did work.. >_< my bad, i'm new in java... and i'm sorry for calling you
    "sir", thanks a lot monica... ^^ by the way, it's 1:00 pm here asia.I'm glad it worked--do you understand what "static" means here?
    No problem about the "sir". I usually use "he" myself, if I don't know whether it should be he/she. And, around here on the forum (and software engineers at most companies), there are certainly more men than women. People tend to look at MLRon and assume my name is "Ron", but that's my last name. :)
    You don't need to call people "sir" or "ma'am" here. Just names or screen names (like MLRon) will do. :)
    Have a nice afternoon, then!

  • Passing an array of objects to a method.

    Hi I'm building a program to act as a CD Collection Database. An array of objects represents the entries: Artist, Album and NUmber of Tracks. What I want to do is in the Menu, user to choose wether he or she wants to Add new CD to collection, print or quit, if he/she does then I call a method addNewEntry, to which i pass the array of objects called array, and I want the user to enter the entries each in turn, after that i want the program to return to the method Menu and ask if he or she wants to quit, print or add new cd. The idea is that the details entered already would be contained in the array of objects [0], so the next set of details go to [1] and then to [2] and so on. I have build up the code at this stage but i get an error while copmiling and im totally stuck. Im a beginner in Java.
    Here is the code:
    //by Andrei Souchinski
    //Mini Project: CD Collection Database
    //Designed for a grade F
    //Defining new class of objects to represent CD database entries.
    //A database entry consists of the artist name, the album name and number of tracks.
    //A single entry can be entered by the user typing the details in and the entry can be printed out.
    import javax.swing.*;
    import java.util.*;
    public class MiniProject
         public static void main (String[] args)     
              System.out.println("\tCD Collection Database\n");
              System.out.println("1. Add new Compact Disk to the Database");
              System.out.println("2. Print out current database entries");
              System.out.println("3. Quit\n");          
              theMenu();
         public static void theMenu()
              CompactDisk [] array = new CompactDisk[20];
              String menu;
              menu = JOptionPane.showInputDialog("What would you like to do?");
              if (menu.equals ("3"))
                   JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
                   System.exit(0);     
              if (menu.equals ("2"))
              if (menu.equals ("1"))
              addNewEntry(array);
              else
                   JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
                   theMenu();
         public int addNewEntry(int newcd[])
                   int i;          
                   newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
                   newcd[i] = (JOptionPane.showInputDialog("Please enter the name of the Album"));
                   newcd[i] = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
    //A Compact Disk entry consists of three attributes: artist name, album and number of tracks
    class CompactDisk
         public String artistname; //Instance variables for artistname, albumname and numberoftracks.
         public String albumname;
         public int numberoftracks;
         public CompactDisk(String n, String a, int t)
         artistname = n; //Stores the 1st argument passed after "new Dates" into day
         albumname = a; //Stores the 2nd argument passed after "new Dates" into month
         numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
         //When called from the main method, prints the contents of
         //artistname, albumname and numberoftracks on to the screen.
         public void printCompactDisk ()
                   String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
                   System.out.println(output);
    }

    //by Andrei Souchinski
    //Mini Project: CD Collection Database
    //Designed for a grade F
    //Defining new class of objects to represent CD database entries.
    //A database entry consists of the artist name, the album name and number of tracks.
    //A single entry can be entered by the user typing the details in and the entry can be printed out.
    import javax.swing.*;
    import java.util.*;
    public class MiniProject
         public static void main (String[] args)     
              System.out.println("\tCD Collection Database\n");
              System.out.println("1. Add new Compact Disk to the Database");
              System.out.println("2. Print out current database entries");
              System.out.println("3. Quit\n");          
                theMenu();
         public static void theMenu()
              String menu;
              menu = JOptionPane.showInputDialog("What would you like to do?");
              if (menu.equals ("3"))
                   JOptionPane.showMessageDialog(null, "Thank You For Using our Service! \nGoodbye!");
                   System.exit(0);     
              if (menu.equals ("2"))
              if (menu.equals ("1"))
              addNewEntry();
              else
                   JOptionPane.showMessageDialog(null, "Please select your choice form the menu");
                   theMenu();
         public static void addNewEntry()
                   CompactDisk [] array = new CompactDisk[20];
                   int i = 0;
                   array.artistname = (JOptionPane.showInputDialog("Please enter the name of the Artist"));
                   array[i].albumname = (JOptionPane.showInputDialog("Please enter the name of the Album"));
                   array[i].numberoftracks = (Integer.parseInt (JOptionPane.showInputDialog("Please enter the number of tracks on this album")));
    //A Compact Disk entry consists of three attributes: artist name, album and number of tracks
    class CompactDisk
         public String artistname; //Instance variables for artistname, albumname and numberoftracks.
         public String albumname;
         public int numberoftracks;
         public CompactDisk(String n, String a, int t)
         artistname = n; //Stores the 1st argument passed after "new Dates" into day
         albumname = a; //Stores the 2nd argument passed after "new Dates" into month
         numberoftracks = t; //Stores the 3rd argument passed after "new Dates" into year
         //When called from the main method, prints the contents of
         //artistname, albumname and numberoftracks on to the screen.
         public void printCompactDisk ()
                   String output = "\n " + artistname + "\n " + albumname + "\n " + numberoftracks;
                   System.out.println(output);
    I've edited the code, itcompiles, but gives an error when i ran it..:(

  • Passing array to a method through actionevent? ??

    what the hell is this guy on about your asking..
    well.. i have a user defined data structures (people)
    and i'm creating my first gui, so i have an action caught with
    public static void main(String[] args)
    int MAX = 1000;
    person[] ppl;
    ppl = new person[MAX];
    public void actionPerformed(ActionEvent e) {
    if(e.getSource() == addNewPerson) {
    //method call in here to add new person
    //but how can i pass the array this far so i can then give it
    //to my method, or am i looking at this all wrong?
    }if as the comments suggests, i'm calling this all wrong, what way should i implement this? i'm basically getting cannot resolve symbol, pointing to my method which adds a new person (so as i said before, it needs to be passed to the method)

    You might want start by reading a few books on OO design first.
    What you will probably want to do is have a class which stores the array and extends ActionListener...
    public class Gui extends ActionListener {
      Person[] ppl = new Person[100];
      Component comp;
      Button addPersonButton;
      public Gui () {
        comp = new .....;
        addPersonButton = new Button("Add person");
        comp.add(addPersonButton);
        comp.addActionListener(this);
      public static void main(String args[]) {
        Gui gui = new Gui();
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == addPersonButton) {
          doAddPerson();
      pulbic void doAddPerson() {
        ppl[0] = ....
    }Hope this shows you a bit more. Not sure how good my design of gui's is though :-/
    Rob.

  • Passing object reference array to a method

    Hi everyone,
    I'm new to the java programming language. I want to create create a array of 50 objects and pass them in to a method in other class.
    Can anyone help me on this problem........................
    Chathu.

    Object[] objectArray = new Object[50];
    objectArray[0] = "Hello World";
    objectArray[1] = new Integer(42);
    myClass.myMethod(objectArray);

  • Passing hard coded array to a method

    how to passing hard coded array to a method
    like method1("eee","eoe","eee",.....)
    which should populate a array of strings (say arr[]) for the method
    what can be done??

    or if you're using Java 5.0 declare the method aspublic void method(String... array) {
    }

  • Passing a whole array through a method

    I need some quick help on how to pass a whole array through the method addCoins(). Here is the code:
    public class Purse {
         private Coin[] coins;
         private int lastIdx;
    public Purse() {
         coins = new Coin[100];
         lastIdx = 0;
    public boolean addCoin(Coin b) {
         if (lastIdx < coins.length) {
              lastIdx++;
              coins[lastIdx] = b;
              return true;
         else {
              return false;
    public boolean addCoins(Coin[] b) {
         if (lastIdx < coins.length) {
              for (b=0; b<99; b++) {
                   coins[b] = b;
         else {
              return false;
    }I figured passing the whole array would be "Coin[] b" but apparently Eclipse says that it can't convert from int to Coin[]. I have no idea what that means. Thanks in advance.

    I need to create 3 classes, Coin, Purse, and TestPurse.
    Coin code:
    public class Coin {
         private String typeOfCoin;
         private double value;
    public Coin(String t, double v) {
         typeOfCoin = t;
         value = v;
    public String toString() {
         return typeOfCoin + value;
    }Purse code:
    public class Purse {
         private Coin[] coins;
         private int lastIdx;
    public Purse() {
         coins = new Coin[100];
         lastIdx = 0;
    public boolean addCoin(Coin b) {
         if (lastIdx < coins.length) {
              lastIdx++;
              coins[lastIdx] = b;
              return true;
         else {
              return false;
    public boolean addCoins(Coin[] b) {
          if (lastIdx < coins.length) {
              for (int i=0; i<coins.length; i++) {
                   coins[i] = b;
         else {
              return false;
    public Coin getReverse() {
         coins = new Coin[0];
         lastIdx = 100;
    }In the Purse class, I need methods addCoin and addCoins that need to return boolean.  addCoin is supposed to add the argument coin as an element of the coins array if there is space.  addCoins neds to add all the coins in the input argument as elements of the coins array if there is space.  I then have to create two methods, getReverse and getValue that take no argument and getReverse that returns an array of type Coin while getValue returns a double.  In getReverse, I create an array simlar to coins but this new array is reverse.  I started on this method but I first need to worry about the addCoin and addCoins method.  For the record, getValue needs to add up the values of all the coins in the purse and return it, which I have no idea how to do that.  That's my next question.
    Edited by: quagmire87 on Dec 1, 2009 4:35 PM
    fixed method addCoins                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem passing multiple array lists to a single method

    Hi, all:
    I have written a generic averaging method that takes an array list full of doubles, adds them all up, divides by the size of the array list, and spits out a double variable. I want to pass it several array lists from another method, and I can't quite figure out how to do it. Here's the averager method:
         public double averagerMethod (ArrayList <Double> arrayList) {
              ArrayList <Double> x = new ArrayList <Double> (arrayList); //the array list of integers being fed into this method.
              double total = 0;//the total of the integers in that array list.
              for (int i = 0; i < x.size(); i++) {//for every element in the array list,
                   double addition = x.get(i);//get each element,
                   total = total + addition; //add it to the total,
              double arrayListSize = x.size();//get the total number of elements in that array list,
              double average = total/arrayListSize;//divide the sum of the elements by the number of elements,
              return average;//return the average.
         }And here's the method that sends several array lists to that method:
         public boolean sameParameterSweep (ArrayList <Double> arrayList) {
              sameParameterSweep = false;//automatically sets the boolean to false.
              arrayList = new ArrayList <Double> (checker);//instantiate an array list that's the same as checker.
              double same = arrayList.get(2); //gets the third value from the array list and casts it to double.
              if (same == before) {//if the third value is the same as the previous row's third value,
                   processARowIntoArrayLists(checker);//send this row to the parseAParameterSweep method.
                   sameParameterSweep = true;//set the parameter sweep to true.
              if (same != before) {//if the third value is NOT the same,
                   averagerMethod(totalTicks);//go average the values in the array lists that have been stored.
                   averagerMethod(totalNumGreens);
                   averagerMethod(totalNumMagentas);
                   sameParameterSweep = false;
              before = same; //problematic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
         return sameParameterSweep;
         }Obviously, the problem is that I'm not passing the array lists from this method to the averager method the right way. What am I doing wrong?

    Encephalopathic wrote:
    There are several issues that I see, but the main one is that you are calculating average results but then just discarding them. You never assign the result to a variable.
    In other words you're doing this:
    averagerMethod(myArrayList);  // this discards the resultinstead of this:
    someDoubleVariable = averagerMethod(myArrayList); // this stores the resultAlso, do you wish to check for zero-sized array lists before calculating? And what would you return if the array list size were zero?So in solving that problem, I've come up with another one that I can't figure out, and I can't fix this problem until I fix that.
    I have several thousand lines of data. They consist of parameter sweeps of given variables. What I'm trying to do is to store pieces of
    data in array lists until the next parameter adjustment happens. When that parameter adjustment happens, I want to take the arraylists
    I've been storing data in, do my averaging thing, and clear the arraylists for the next set of runs under a given parameter set.
    Here's the issue: I'm having the devil of a time telling my application that a given parameter run is over. Imagine me doing stuff to several variables (number of solders, number of greens, number of magentas) and getting columns of output. My data will hold constant the number of soldiers, and for, say, ten runs at 100 soldiers, I'll get varying numbers of greens and magentas at the end of each of those ten runs. When I switch to 150 soldiers to generate data for ten more runs, and so forth, I need to average the number of greens and magentas at the end of the previous set of ten runs. My problem is that I can't figure out how to tell my app that a given parameter run is over.
    I have it set up so that I take my data file of, say, ten thousand lines, and read each line into a scanner to do stuff with. I need to check a given line's third value, and compare it to the previous line's third value (that's the number of soldiers). If this line has a third value that is the same as the previous line's third value, send this line to the other methods that break it up and store it. If this line has a third value that is NOT the same as the previous line's third value, go calculate the averages, clear those array lists, and begin a new chunk of data by sending this line to the other methods that break it up and store it.
    This is not as trivial a problem as it would seem at first: I can't figure out how to check the previous line's third value. I've written a lot of torturous code, but I just deleted it because I kept getting myself in deeper and deeper with added methods. How can I check the previous value of an array list that's NOT the one I'm fiddling with right now? Here's the method I use to create the array lists of lines of doubles:
         public void parseMyFileLineByLine() {
              totalNumGreens = new ArrayList <Double>();//the total number of greens for a given parameter sweep
              totalNumMagentas = new ArrayList <Double>();//the total number of magentas for a given parameter sweep.
              totalTicks = new ArrayList <Double>();//the total number of ticks it took to settle for a given parameter sweep.
              for (int i = 8; i < rowStorer.size() - 2; i++) {//for each line,
                   checker = new ArrayList <Double>();//instantiates an array list to store each piece in that row.
                   String nextLine = rowStorer.get(i); //instantiate a string that contains all the information in that line.
                   try {
                        Scanner rowScanner = new Scanner (nextLine); //instantiates a scanner for the row under analysis.
                        rowScanner.useDelimiter(",\\s*");//that scanner can use whitespace or commas as the delimiter between information.
                        while (rowScanner.hasNext()) {//while there's still information in that scanner,
                             String piece = rowScanner.next(); //gets each piece of information from the row scanner.
                             double x = Double.valueOf(piece);//casts that stringed piece to a double.
                             checker.add(x);//adds those doubles to the array list checker.
                   catch (NoSuchElementException nsee) {
                        nsee.printStackTrace();
                   //System.out.println("checker contains: " + checker);
                   processARowIntoArrayLists(checker);//sends checker to the method that splits it up into its columns.
         }

  • Trouble while passing an array as a parameter to an JDBC Control

    Hi everyone, recently I have upgraded my WLS Workshop 8.1 application to WLS 10gR3 using the workshop 8.1 application upgrade but after the upgrade to beehive controls I'm having troubles in a couple of methods that receive an array as a parameter. One of the methods is the following:
    * @jc:sql array-max-length="all" max-rows="all"
    * statement::
    * select COUNT(*) FROM (
    * SELECT la.lea_gkey,la.eme_gkey
    * FROM (SELECT gkey, name, role FROM employees WHERE {sql:fn in(gkey,{emeGkeyArray})}) e,
    * lead_assignees la,
    * leads le,
    * cities ct,
    * (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TARGET') targets,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100
    * WHERE e.gkey = la.eme_gkey
    * AND la.lea_gkey = le.gkey
    * AND le.city = ct.gkey(+)
    * AND le.gkey = cn.lea_gkey(+)
    * AND le.gkey = targets.lea_gkey(+)
    * AND le.gkey = top5.lea_gkey(+)
    * AND le.gkey = top100.lea_gkey(+)
    * {sql: whereClause}
    * UNION
    * SELECT DISTINCT la.lea_gkey,la.eme_gkey
    * FROM (SELECT gkey, name, role FROM employees WHERE {sql:fn in(gkey,{emeGkeyArray})}) e,
    * lead_assignees la,
    * shared_accounts sa,
    * leads le,
    * cities ct,
    * employees asign,
    * (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TARGET') targets,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100
    * WHERE e.gkey = sa.eme_gkey
    * AND asign.gkey = la.eme_gkey
    * AND asign.active='X'
    * AND sa.lea_gkey = le.gkey
    * AND sa.lea_gkey = la.lea_gkey
    * AND le.city = ct.gkey(+)
    * AND le.gkey = cn.lea_gkey(+)
    * AND le.gkey = targets.lea_gkey(+)
    * AND le.gkey = top5.lea_gkey(+)
    * AND le.gkey = top100.lea_gkey(+)
    * {sql: assigneeClause}
    * UNION
    * SELECT DISTINCT la.lea_gkey,la.eme_gkey
    * FROM (SELECT gkey, name, role FROM employees WHERE {sql:fn in(gkey,{emeGkeyArray})}) e,
    * lead_assignees la,
    * shared_accounts sa,
    * leads le,
    * cities ct,
    * (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TARGET') targets,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5,
    * (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100
    * WHERE e.gkey = la.eme_gkey
    * AND sa.lea_gkey = le.gkey
    * AND sa.lea_gkey = la.lea_gkey
    * AND le.city = ct.gkey(+)
    * AND le.gkey = cn.lea_gkey(+)
    * AND le.gkey = targets.lea_gkey(+)
    * AND le.gkey = top5.lea_gkey(+)
    * AND le.gkey = top100.lea_gkey(+)
    * {sql: sharedClause})::
    @JdbcControl.SQL(arrayMaxLength = 0,
    maxRows = JdbcControl.MAXROWS_ALL,
    statement = "select COUNT(*) FROM ( SELECT la.lea_gkey,la.eme_gkey FROM (SELECT gkey, name, role FROM employees WHERE {sql:fn in(gkey,{emeGkeyArray})}) e, lead_assignees la, leads le, cities ct, (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TARGET') targets, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100 WHERE e.gkey = la.eme_gkey AND la.lea_gkey = le.gkey AND le.city = ct.gkey(+) AND le.gkey = cn.lea_gkey(+) AND le.gkey = targets.lea_gkey(+) AND le.gkey = top5.lea_gkey(+) AND le.gkey = top100.lea_gkey(+) {sql: whereClause} UNION SELECT DISTINCT la.lea_gkey,la.eme_gkey FROM (SELECT gkey, name, role FROM employees WHERE {sql:fn in(gkey,{emeGkeyArray})}) e, lead_assignees la, shared_accounts sa, leads le, cities ct, employees asign, (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TARGET') targets, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100 WHERE e.gkey = sa.eme_gkey AND asign.gkey = la.eme_gkey AND asign.active='X' AND sa.lea_gkey = le.gkey AND sa.lea_gkey = la.lea_gkey AND le.city = ct.gkey(+) AND le.gkey = cn.lea_gkey(+) AND le.gkey = targets.lea_gkey(+) AND le.gkey = top5.lea_gkey(+) AND le.gkey = top100.lea_gkey(+) {sql: assigneeClause} UNION SELECT DISTINCT la.lea_gkey,la.eme_gkey FROM (SELECT gkey, name, role FROM employees WHERE {sql:fn in(gkey,{emeGkeyArray})}) e, lead_assignees la, shared_accounts sa, leads le, cities ct, (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TARGET') targets, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100 WHERE e.gkey = la.eme_gkey AND sa.lea_gkey = le.gkey AND sa.lea_gkey = la.lea_gkey AND le.city = ct.gkey(+) AND le.gkey = cn.lea_gkey(+) AND le.gkey = targets.lea_gkey(+) AND le.gkey = top5.lea_gkey(+) AND le.gkey = top100.lea_gkey(+) {sql: sharedClause})")
    public Long getProspectsCount(String[] emeGkeyArray, String whereClause, String assigneeClause, String sharedClause) throws SQLException;
    The execution of the method is the following:
    pendingApprovals = leadsListingDB.getProspectsCount(employeeHierarchyArray, pendingApprovalsClause, pendingApprovalsClause, pendingApprovalsClause);
    When the method is executed all the String parameters (whereClause, assigneeClause & sharedClause) are replaced well except the array parameter (emeGkeyArray) so the execution throws the following exception because the array is not replaced:
    <Jan 20, 2010 1:01:26 PM CST> <Debug> <org.apache.beehive.controls.system.jdbc.JdbcControlImpl> <BEA-000000> <Enter: onAquire()>
    <Jan 20, 2010 1:01:26 PM CST> <Debug> <org.apache.beehive.controls.system.jdbc.JdbcControlImpl> <BEA-000000> <Enter: invoke()>
    <Jan 20, 2010 1:01:26 PM CST> <Info> <org.apache.beehive.controls.system.jdbc.JdbcControlImpl> <BEA-000000> <PreparedStatement: select COUNT(*) FROM ( SELECT la.lea_gkey,la.eme_gkey FROM (SELECT gkey, n
    me, role FROM employees WHERE (gkey IN ())) e, lead_assignees la, leads le, cities ct, (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn, (SELECT lea_gkey, tag FROM lead
    tags WHERE tag = 'TARGET') targets, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100 WHERE e.gkey = la.eme_gkey AND la.l
    a_gkey = le.gkey AND le.city = ct.gkey(+) AND le.gkey = cn.lea_gkey(+) AND le.gkey = targets.lea_gkey(+) AND le.gkey = top5.lea_gkey(+) AND le.gkey = top100.lea_gkey(+) AND LA.ACTIVE = 'X' AND LE.WE
    KLY_POTENTIAL > 0 AND (LE.APPROVED IS NULL OR LE.APPROVED != 'Y') AND LA.SALE_STAGE IN(3034,3005) UNION SELECT DISTINCT la.lea_gkey,la.eme_gkey FROM (SELECT gkey, name, role FROM employees WHERE (gkey I
    ())) e, lead_assignees la, shared_accounts sa, leads le, cities ct, employees asign, (select lea_gkey,name,email,phone,title from contacts where principal = 'X') cn, (SELECT lea_gkey, tag FROM lea
    tags WHERE tag = 'TARGET') targets,  (SELECT leagkey, tag FROM lead_tags WHERE tag = 'TOP5') top5, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP100') top100 WHERE e.gkey = sa.eme_gkey AND asi
    n.gkey = la.eme_gkey AND asign.active='X' AND sa.lea_gkey = le.gkey AND sa.lea_gkey = la.lea_gkey AND le.city = ct.gkey(+) AND le.gkey = cn.lea_gkey(+) AND le.gkey = targets.lea_gkey(+) AND le.gkey
    = top5.lea_gkey(+) AND le.gkey = top100.lea_gkey(+) AND LA.ACTIVE = 'X' AND LE.WEEKLY_POTENTIAL > 0 AND (LE.APPROVED IS NULL OR LE.APPROVED != 'Y') AND LA.SALE_STAGE IN(3034,3005) UNION SELECT DISTINCT
    la.lea_gkey,la.eme_gkey FROM (SELECT gkey, name, role FROM employees WHERE (gkey IN ())) e, lead_assignees la, shared_accounts sa, leads le, cities ct, (select lea_gkey,name,email,phone,title from c
    ntacts where principal = 'X') cn, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TARGET') targets, (SELECT lea_gkey, tag FROM lead_tags WHERE tag = 'TOP5') top5, (SELECT lea_gkey, tag FROM lead_tags
    WHERE tag = 'TOP100') top100 WHERE e.gkey = la.eme_gkey AND sa.lea_gkey = le.gkey AND sa.lea_gkey = la.lea_gkey AND le.city = ct.gkey(+) AND le.gkey = cn.lea_gkey(+) AND le.gkey = targets.lea_gkey(+
    AND le.gkey = top5.lea_gkey(+) AND le.gkey = top100.lea_gkey(+) AND LA.ACTIVE = 'X' AND LE.WEEKLY_POTENTIAL > 0 AND (LE.APPROVED IS NULL OR LE.APPROVED != 'Y') AND LA.SALE_STAGE IN(3034,3005)) Params:
    {}>
    <Jan 20, 2010 1:01:26 PM CST> <Debug> <org.apache.beehive.netui.pageflow.FlowController> <BEA-000000> <Invoking exception handler method handleException(java.lang.Exception, ...)>
    [LeadsMailer] Unhandled exception caught in Global.app:
    java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
    So the big question is if that behavior is due to a bug of I'm doing something wrong. Do someone can give me an advice about this problem because the array parameter has no problems in workshop 8.1?
    Thanks in advance!

    Greetings
    I may not have an answer for you, but i am in the same boat! I am trying to pass an array to store in the database. I have 2 out of 8 columns that need to be stored as arrays. Everything saves EXEPT for the 2 arrays in question. I am using BEEHIVE with my web app. The strange thing is that i do not receive any syntax errors or runtime codes. I am still searching for an answer. If i find anything out, i will let you know.
    John Miller
    [email protected]

Maybe you are looking for

  • How to purchase data in uk for ipad 2

    I'm going to England soon and would like to buy data there like I often do by the month from att. Not sure what plans are offered and does it work the same way as here by just going online and buying it or do I. Need a SIM card

  • Master IDOC but not the communication IDOC

    Hi what is master IDOC and the communication IDOC what is the diff? i have installed sap gui in my system and how to connect the sapserver through internet?

  • I am trying to download pictures off my Samsung "Galaxy" phone but I am having no luck

    I am trying to download pictures from a Samsung "Galaxy" phone to my macbook.  Any suggestions?

  • Noted items Creation

    What are all the Steps needed to create a Noted Item for a Customer? Using FBKP transaction for the Account Type "D" with the FLAG   "F"       , In the Properties Tab    Should I need to Select the "Noted Items"   What is the purpose of Target GL Ind

  • Hex Ascii conversion Problem

    Hi. I am working on a project where I send commands to the serial port. I am using the java.comm.*; library and for now, using the provided sample program to send and receive commands. Before using java, I used a program called terminal.exe, to send