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?

Similar Messages

  • Passing array to another class?

    I have this code which reads in a text file and stores the data in the race array.
    import java.io.*;
    import java.util.*;
    public class Runner {
        public static void main(String[] args) throws IOException {
            BufferedReader in = new BufferedReader(new FileReader("race1.txt"));
            String line;
            while ((line = in.readLine()) != null) {
                String[] race = line.split(",");
                int position = Integer.parseInt(race[0]);
                String name = race[1];
                String team = race[2];
                System.out.println("position=" + position + ", name=" + name + ", team=" + team);
                   in.close();
       }What I want to do is use the race array in another class called Results to perform some calculation methods with the results. So far I haven't been able to get anything to work. Anyone got any advice?

    I was mistaken. Your array isn't of type Race[] or Runner[], but of String[]. Change the declaration accordingly.
    It's not difficult to understand. At one point, you declare a method and define the parameters (in this case a String[]). Once you do that, you have to make sure that you actually do pass a String[] if the method needs one.
    There's no difference in handling parameters, regardless if it's an object, an array, or a primitive value.

  • How can I use my array in another method.... Or better yet, what's wrong?

    I guess I'll show you what I am trying to do rather and then explain it
    public class arraycalc
    int[] dog;
    public void arraycalc()
    dog = new int[2];
    public void setSize(int size)
    dog[1] = size;
    public int getSize()
    return dog[1];
    This gives me a null pointer exception...
    How can I use my array from other methods?

    You have to make the array static. :)
    Although I must admit, this is rather bad usage. What you want to do is use an object constructor to make this class an object type, and then create the array in your main class using this type, and then call the methods from this class to modify your array. Creating the array inside the other method leads to a whole bunch of other stuff that's ... well, bad. :)
    Another thing: Because you're creating your array inside this class and you want to call your array from another class, you need to make the array static; to make it static, you must make your methods static. And according to my most ingenious computer science teacher, STATIC METHODS SUCK. :D
    So, if you want to stick with your layout, it would look like:
    public class arraycalc
         static int[] dog;
         public static void arraycalc()
              dog = new int[2];
         public static void setSize(int size)
              dog[1] = size;
         public static int getSize()
              return dog[1];
    }But I must warn you, that is absolutely horrible code, and you shouldn't use it. In fact, I don't even know why I posted it.
    You should definitely read up on OOP, as this problem would be better solved by creating a new object type.

  • Passing array values to methods & Classes

    Hi,
    I have written the following two classes, I want to pass the value from one class - insersortest to the other class what kind of return statement do I do ? I am not sure what does this Comparable object do in this program ? I am trying the program (algorithm specfieid) from one of the Data Structure book.
    import java.io.*;
    import java.lang.*;
    public class Insersortest
    public static void main(String args[]) throws IOException
    Insersort ghl = new Insersort();
              Comparable a[] = {1, 3, 5, 9, 1};          
                   System.out.println("Detecting duplicates"+ ghl.insertA(a));               
    -=-=-=-
    class Insersort
    public static int insertA( Comparable [ ] a )
    for( int p = 1; p < a.length; p++ )
    Comparable tmp = a[ p ];
    int j = p;
    for( ; j > 0 && tmp.compareTo( a[ j - 1 ] ) < 0; j-- )
    a[ j ] = a[ j - 1 ];
    a[ j ] = tmp;
    Could somebody provide their view please.
    PK

    You return arrays just like any object:
    public Object[] getArray()Comparable is an interface. Any object that implements Comparable (and can therefore be stored in a Comparable's reference) is guarenteed to have a compareTo method.
    Does that help?

  • 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 Array to a method

    Hi,
    There is a class MyClass that implements Serializable. I need to create array of this class and pass to a method.
    In java, this can be done as following:
                   MyClass[] myClassVariables=new MyClass[2];
                   MyClass myClassInstance1=new MyClass();
                   MyClass myClassInstance2=new MyClass();
                   myClassVariables[0]=myClassInstance1;
                   myClassVariables[1]=myClassInstance2;
                   String message = getValues(myClassVariables);
    import java.io.Serializable;
    public class MyClass implements Serializable{
    public String getValues(MyClass[] myClassVariables)
    When I implement this in a workflow, I get the following error:
    XPRESS exception:
    com.waveset.util.WavesetException: Couldn't find method getValues(java.lang.String, java.lang.String) in class MyClass
    java.lang.NoSuchMethodException: MyClass.getValues(java.lang.String, java.util.ArrayList)
    Code I am using is as following:
    <set name='myClassInstance1'>
    <new class='com.marathon.MyClass'/>
    </set>
    <set name='myClassInstance2'>
    <new class='com.marathon.MyClass'/>
    </set>
    <set name='myList'>
    <new class='java.util.ArrayList'/>
    </set>
    <set name='myClassVariables'>
    <list>
    <ref>myClassInstance1</ref>
    <ref>myClassInstance2</ref>
    </list>
    </set>
    <set name='message'>
    <invoke name='getValues' class='MyClass'>
    <ref>myClassVariables</ref>
    </invoke>
    </set>
    <ref>message</ref>
    Please help me,
    Thanks

    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.

  • Displaying array from another method

    Hello for this code I want to display the array from the first method in the second method although when I run it, it displays 6 times the whole array - well the the last iteration shows the whole array. I have only just started using different methods.
    Please could someone say why this is happening.
    Cheers
    John
    import java.util.*;
    public class Lottery
         public static void main(String[] argStrings)
              int[] lotteryArray = new int[6];
              for(int count = 0; count < 6; count++)
                   double randomNumber = Math.random();
                   double biggerRandom = (randomNumber * 50);
                   int integerNumber = (int)biggerRandom;
                   lotteryArray[count] = integerNumber;
                   displayNumbers(lotteryArray);
         public static void displayNumbers(int[] lotteryArray)
              System.out.println("Lottery numbers are:");
              for(int i = 0; i < lotteryArray.length; i++)
                   System.out.print(lotteryArray[i] + " ");
              System.out.println();
    }

    Well I know your right but actualy getting this to work for my program is proving hard. This is my progress so far:
    Cheers
    John
    public static void main(String[] argStrings)
              int[] lotteryArray = new int[6];
              int p = 0;
              boolean duplicate = false;
              while(p < 6)
                   for(int count = 0; count < lotteryArray.length; count++)
                        double randomNumber = Math.random();
                        double biggerRandom = (randomNumber * 50);
                        int integerNumber = (int)biggerRandom;
                        if (lotteryArray == lotteryArray[count])
                             duplicate = true;
                        if (duplicate == false) //not a duplicate
                             lotteryArray[++count] = integerNumber;
                   displayNumbers(lotteryArray);
         }

  • How do I access array elements in one method from another method?

    Hi all!
    How do I access the array's elements from another method so that method 2 can have access to method 1's array elements? Thanks for any help!
    I am trying to create a simply program that will use a method to create an array and a SEPARATE method that will sort the array's elements (without using java's built in array features). I can create the program by simply having one method and sorting the array within that same method, BUT I want to sort the array from another method.
    Here's my code so far:
    public class ArraySort {
       public static void createArray(int size){
           double myArray[] = new double[size];    //create my new array
           for(int j=0; j < myArray.length; j++)
              myArray[j] = (200.0 * Math.random() + 1.0);   //fill the array with random numbers
       public static void sortArray(){
           // I WANT THIS METHOD TO ACCESS THE ARRAY ELEMENTS IN THE METHOD ABOVE, BUT DON'T KNOW
          //  HOW???? Please help!
        public static void main(String[] args) {
            createArray(4);    //call to create the array
    }Thanks again!
    - Johnny

    Thanks for the help all! I ve managed to get the program working, using java's built in array sort, but when i try to call on the array sort method from WITHIN my main method, nothing happens!
    Can somebody please tell me why I am not able to call on the sort method from within my main class???? Thanks!
    public class ArraySort {
       public void createArray(double[] arrayName, int size){
           double myArray[] = new double[size];  //create new array
           for(int j=0; j < myArray.length; j++)
              myArray[j] = (200.0 * Math.random() + 1.0);    //populate array with
           }                                                 //random Numbers
           sortArray(myArray); 
       } //Sort array(if I delete this & try to use it in Main method --> doesn't work???
       public void sortArray(double[] arrayName){
           DecimalFormat time = new DecimalFormat("0.00");
           Arrays.sort(arrayName);      //sort array using Java's built in array method
           for(int i = 0; i <arrayName.length; i++)
               System.out.println(time.format(arrayName)); //print arary elements
    public static void main(String[] args) {
    ArraySort newArray = new ArraySort(); //create a new instance
    double myArray[] = new double[0]; //create a new double array
    newArray.createArray(myArray,4); //build the array of indicated size
    //newArray.sortArray(myArray); //This will not work???? WHY?????//

  • Passing parameters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    I do some changes to them and expect the changed
    objects to be available in the calling methodIf you modify an object passed to a method, then the changes made to that object will be visible as soon as they are made.
    If you change the parameter so that it references some other object, this will NOT be seen in the calling method.
    You can "fake" it by putting the object in question in an array and passing the array. Better though is to just not expect methods to be able to change references they are passed to point at some other object.

  • Passing paramaters to a method

    I am passing objects to another method.
    I do some changes to them and expect the changed objects to be available in the calling method ( since they are supposedely passed by reference) when the execution is returned to it. However, I don't get the changed objects but rather the old ones, before the method execution.
    Can someone explain?
    Thanks,
    Boris.

    This is an extremely common question. A search through this forum would be very useful to you.
    Java does not pass-by-reference in the same way C/C++ do. When you pass an object to a method, you can change the contents of the object using its methods and see the changes after the method completes in the calling method. In this way Java is similar to C/C++.
    However, you cannot change an object to equal another object or a new object inside a method and expect the changes to be visible after the method completes in the calling method.
    Here is an example.
    This will show changes and the line "String" would be printed.
      StringBuffer sb = new StringBuffer();
      method(sb);
      System.out.println(sb);
      public void method(StringBuffer buf) {
        buf.append("String");
      }However, this would not show changes and the line "Old String would be printed:
      String string = "Old String";
      method(string);
      System.out.println(string);
      public void method(String string) {
        string = "New String";
        // string.concat("New String) would also fail to work

  • Pass array on to another class

    Hi. Simple question here.
    I have two classes and in one I have an array. I want to pass it on to the other class so I can use the values and stuff there. How do I do that?

    You don't pass things to classes. You pass them to constructors or methods of a class or instance of one.
    If you do this, for example:
    System.out.println("Hello world");
    you are passing a String argument to the println method.
    You can similarly pass your array to a method of some class, if that method accepts an array as a parameter.
    P.S. You're welcome. Obviously you didn't get hit by a bus and couldn't reply with a simple "thank you", as you posted another topic a day or so later than this. But, you're welcome.

  • Passing argstrings[1] to another method

    Hello I want to pass argstrings[1] to another method. Other stuff is being passed there to. Before I passed argstrings[1] the other stuff worked, now it does not.
    Please tell me why I am getting compilation errors.
    Thanks
    public static void main(String[] argStrings)
            String filePath = null;
            if(argStrings.length != 0)
                 filePath = argStrings[0];
            else
                 System.out.println("Enter a directory please");// Else you have to enter a directory
                 Scanner scan = new Scanner(System.in);
                    filePath = scan.nextLine();
            String copyDate = argStrings[1];
            Date dateToLookFor = new Date(copyDate);
            listFiles(filePath);// this no longer works as of the new log(datetolookfor)
            log(dateToLookFor);// just wanna pass this to the next method
       private static void log(File[] files, Date dateToLookFor)
       {

    Well i only get one compile error, cheers.
    So please could you help me what i have to do to this mess in order for it to work:
    Or just edit the code as I dont think there is much to do:
    Thanks
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    * This application identifies files which could potentially be archived
    * and copied. A file is to be archived if the last modified date is more
    * than 100 days ago. A file is to be copied if it has been modified since
    * a given time. Only nominated extensions are to be considered. The java.
    * util.Calendar class contains relevant methods for comparing times and dates.
    * For instance, a command line of: java CrawlerApp Knuth 2005-12-28 php html
    * Will nominate for archiving or copying only php or html files in the Knuth
    * directory tree. It will only nominate for copying files modified after
    * midnight on the 28th of December, 2005.
    * The output from this application is two files (called archive.txt and copy.txt)
    * containing the names of files to be archived, and those which may be copied.
    * The names will follow the convention specified in the create application.
    * These two text files must appear in the root directory (Knuth, in this example).
    public class Crawler
       public static void main(String[] argStrings)
            String name = null;
            if(argStrings.length != 0)
                 name = argStrings[0];
            else
                 System.out.println("Enter a directory please");// Else you have to enter a directory
                 Scanner scan = new Scanner(System.in);
                    name = scan.nextLine();
            String copyDate = argStrings[1];
            listFiles(name, copyDate);
       private static void log(String copyDate, File[] files)
            PrintStream archivePS = null;
            PrintStream copyPS = null;
            try
                 archivePS = new PrintStream("archive.txt");
                 copyPS = new PrintStream("copy.txt");
                 // instantiate cutoff Calendar instance to test files with
                   Calendar cutoff = Calendar.getInstance();
                   // time now
               Date now = new Date();
                   // set cutoff time with current time
                   cutoff.setTime(now);
                   // subtract 100 days from current time
                   cutoff.add(Calendar.DAY_OF_YEAR, -100);//
                 Calendar calendar = Calendar.getInstance();
                 for(int j = 0; j < files.length; j++)
                      // get last modified time of file
                      long lastModified = files[j].lastModified();
                      // convert lastModified to a date
                      Date lastMod = new Date(lastModified);
                      // set the time for the Calendar instance with lastMod
                      calendar.setTime(lastMod);
                      // test against cutoff Calendar instance variable
                     if(lastMod.before(cutoff.getTime()))
                           archivePS.println(files[j]);
                         if(lastMod.before(cutoff.getTime()))
                              copyPS.println(files[j]);
                         // I will do copy later, just want to see if this works
            catch(FileNotFoundException fnfe)
                 System.err.println("Log error: " + fnfe.getMessage());
            catch(IOException ioe)
                 System.err.println("I/O exception: " + ioe.getMessage());
       private static void listFiles(String name, String copyDate)
           File f = new File(name);// Try to get a list of files in the directory
           File[] files = f.listFiles();// Make array of all the files in that directory
           log(files, copyDate);
           if(f.isDirectory())// If the argStrings[0] is a directory then do the following
               File[] children = f.listFiles(HTMLfilter);// Make an array of html files
               System.out.println("HTML files in " + name + " directory = " + children.length);
               File[] phpFiles = f.listFiles(PHPFilter);// Make an array of php files
               System.out.println("PHP files in " + name + " directory = " + phpFiles.length);
       private static FileFilter HTMLfilter = new FileFilter()
           public boolean accept(File f)// Accept directory Knuth
               //if(f.isDirectory()) return true;
               String name = f.getName().toLowerCase();
               return name.endsWith("html");
               //if(file is 100 days old)
       private static FileFilter PHPFilter = new FileFilter()
            public boolean accept(File f)
                 //if(f.isDirectory()) return true;
                 String name = f.getName().toLowerCase();
                 return name.endsWith("php");
    }

  • How can i pass array as argument in magento api method calling using sudzc API in iphone Native APP

    0down votefavorite
    I am implementing magento standard api method in native iphone app. I use webservice generated by sudzc. To call method I use:
    [service call:self action:@selector(callHandler:) sessionId:@" " resourcePath:@" " args:@""];
    When I used methods e.g. cart.info or product.info in which I have to pass one parameter; it gives valid response. But when I used method e.g. cart_product.add in which I have to pass an argument as value of array it gives error
    SQLSTATE[42000]: Syntax error or access violation:
        1064 You have an error in your SQL syntax;
        check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
    I have tested in SOAP UI also. There also it gives me same error. But same method works in PHP file. Even I tried by creating same soap request which I created using JavaScript but still it doesn't work.
    Can anyone help me to pass array as a parameter using sudzc api to call magento web services?

    There is an error in your SQL.

  • How to pass value in array to another procedure?

    Hello.
    I have created application by Developer form9i.
    And I have some problem about passing value in array to another procedure.
    My code is :
    PROCEDURE p_add_array (col_no in number,
    col_val in varchar2) IS     
    type xrecord is record(col number,vcol varchar2(1000));
    xrec xrecord;
    type varraytype is varying array(42) of xrecord;     
    xvartab varraytype := varraytype();
    alert number;
    BEGIN
    set_application_property(cursor_style,'busy');
    xrec.col := col_no;
    xrec.vcol := col_val;
    xvartab.extend(1);
    xvartab(col) := xrec;
    EXCEPTION
    when others then
    set_application_property(cursor_style,'default');
    alert := f_show_alert('!Error ORA-'||
    to_char(DBMS_ERROR_CODE)||' '||
    substr(DBMS_ERROR_TEXT,1,240),
    'al_stop');          
    END;
    And I want to have
    PROCEDURE p_print_arrey is
    BEGIN
    END;
    So how to bring value of xvartab( ) in p_add_array to use in p_print_array?
    Anybody please help me solve this ploblem.

    Hi,
    Instead of declaring the array locally within the procedure (i.e. p_add_array), define it in the package specification (i.e. Under Program Units).
    -- Shailender Mehta --

  • How to pass a internal table used in one method to another method in a view

    hi all,
    Is it possible to pass a internal table from one method to another method in a view??
    If so , kindly help me.

    Hi Bala,
    If you want to pass this internal table between different methods of the same view then write the contents of this internal table to a context node of your view using BIND_TABLE. You can then read the contents of this internal table from the other method using the reference of that node & the GET_STATIC_ATTRIBUTES_TABLE method.
    However if you want to pass the internal table between methods of different views then create a context node at the COMPONENTCONTROLLER level & then do a context mapping of this node to your local views context in both your views. You can follow the same BIND_TABLE & GET_STATIC_ATTRIBUTES_TABLE methods approach.
    Regards,
    Uday

Maybe you are looking for

  • Digital signatures in real life

    Hi, I've been trying to grok the concept for a while, not without a modicum of success. Yet the big picture escapes me. I'm interested primarily in electronic document workflow as a substitute for classic paper document workflow. There must be softwa

  • Ajax components in Netbeans 6 M10

    I could not fine any Ajax components in Netbeans 6 M10. Anyone please advice me how to get it or import it. Thank you very much.

  • Connecting a Dell B22 FEX to Nexus 6001 and storage

    Hi Folks, We have a setup where we are running a Dell B22 FEX in Blade enviornment and want to connect the B22 FEX to a cisco Nexus 6001 switch. As per NX-OS release note, B22 FEX and 6001 Nexus connectivity is supported. Now after connecting to Nexu

  • What is the correct file version?

    Why does it appear that there are differing file versions for Firefox, Thunderbird and SeaMonkey depending where you look? Windows Explorer show one file version for example 1.9.2.3951 is the 3.6.12 product version but yet our SCCM reports 1.9.2.12 f

  • Display Alternative Account in Additional Data screen of FB03

    Dear SAP experts, Transaction code FB03's screen does have an alternative account column. But I want to display Alternative account when I click on each account (in line item of FB03 screen) or display alternative account in Additional Data screen of