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

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 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 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.

  • 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.
         }

  • 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 ;->

Maybe you are looking for

  • Scanning Problem - HP Officejet Pro 8500a

    I've had a problem with scanning from my iMac running 10.6.8 (and lesser versions) to my HP Officejet Pro 8500a over my wifi network. Printing works flawlessly. When I try to scan a single-page document or photo, it scans only about HALF of the page

  • PERFORM ENTRY_NEU IN PROGRAM parameters error

    Hi, Looking for the cause of this error please: "Short text: Too many parameters specified with PERFORM. The reason for the exception is: A PERFORM was used to call the routine "ENTRY_NEU" of the program "Z_PGM". This routine contains 2 formal parame

  • Retrieve custom property for a user

    Within a custom portlet, how would I obtain custom properites of the current user viewing the portlet? For example, if a user had property "Favorite Food" populated and I wanted my portlet to display recipes using his/her favorite food.

  • Secure Erase of files stored on file server

    Hi there Not sure if this is the right forum for this, but here goes... I have client machines set up for 'Secure Empty Trash', but is there a way I can ensure the same erase 'level' of files that are deleted from the file server (running OSX Server

  • I need to remove the first device on my account from at many years ago. How? Device long gone.

    I've had my account for many years and didn't know anything about deauthorizing devices back then. I've maxed out my number of devices at five and can't add anymore. I know the first device is long gone in a recycling bin some many years ago (or not,