Array and methods

Hi, im trying to create a Phonebook class, I have succesfully added a method that finds the name and last name of the person entered by the user, however I cant seem to get my delete method working, the way how the delete method is supposed to work is that the user enters a name and lastname and then the array containing that number deletes the entry or else it displays an error message saying it hasnt been found.
this is what I have so far
Modify the program so that it can deal with an array that has null in some cells.
Now alter the program so that the user has a choice of three actions:
1. Search for a name (as above).
2. Add a new name and phone number to the array.
3. Delete a name (and phone number) from the array.
(Simple Method:) To delete a name and number from the array,
first find its cell, then assign null to that cell.
(The PhoneEntry previously referenced by that cell will be collected by the garbage collector.)
If the name to delete is not in the array, report an error.
(Better Method:) As it now stands, the program must deal with an array that might
have null values scattered throughout its cells. This is awkward and for a large array is
inefficient. A better notion is to keep the array organized so that all the nulls are together
at the end. Now when the array is searched, the first null signals the end of useful data and the search stops.
To delete a name and number from such an array, first find the name's cell.
If the name to delete is not in the array, report an error. Now copy the reference in the
last non-null cell to the deleted name's cell. Set the last non-null cell to to null.
Now the deleted PhoneEntry is garbage, and all the array still has all the nulls at the end.
class PhoneEntry
String firstname;
String lastname;
String phone;
PhoneEntry( String ln,String fn, String p )
lastname=ln;
firstname = fn;
phone = p;
class PhoneBook
PhoneEntry[] phoneBook;
final int ARRAY_LENGTH= 10;
PhoneBook() // constructor
phoneBook = new PhoneEntry[ARRAY_LENGTH] ;
phoneBook[0] = new PhoneEntry("Smith",
"John", "(418)665-1223");
phoneBook[1] = new PhoneEntry(
"Tony", "Gouidan", "(860)399-3044");
phoneBook[2] = new PhoneEntry(
"Jane", "Maryl", "(815)439-9271");
phoneBook[3] = new PhoneEntry(
"Babe","Jess", "(312)223-1937");
phoneBook[4] = new PhoneEntry(
"Wainstain" , "Emily", "(913)883-2874");
PhoneEntry search( String targetLName, String targetName)
boolean value= false;     
     for (int j=0; j< phoneBook.length-j-1; j++)
          String lname= phoneBook[j].lastname.toUpperCase();
               String fname= phoneBook[j].firstname.toUpperCase();
          if ( targetLName.equals(lname) && targetName.equals("") )
                    System.out.println(phoneBook[j].lastname+" "+phoneBook[j].firstname+
                    " : "+phoneBook[j].phone);
                    value=true;     
               if ( targetName.equals(fname) && targetLName.equals("") )
                    System.out.println(phoneBook[j].lastname+" "+phoneBook[j].firstname+
                    " : "+phoneBook[j].phone);
                    value= true;
          else if ( targetLName.equals(lname) && targetName.equals(fname) )
                    value= true;
                    int index=j;
                    return phoneBook[j];
if (value==false)
               System.out.println("Name not found");
return null;
PhoneEntry add(String targetLName,String targetName, String number)
     boolean value = false;
     for (int j=0; j< phoneBook.length-1; j++)
               if (phoneBook[j]==null)
                    value= true;
                    phoneBook[j] = new PhoneEntry (targetLName,targetName, number);
                    System.out.println("New number added in phoneBook ["+j+"]");
                    return phoneBook[j];
          if (value==false)
               System.out.println("No space available");
     return null;
//THIS IS WHERE IM HAVING TROUBLE, THE THING IS THAT I DONT EVEN KNOW HOW TO START THE METHOD, SOME ORIENTATION OR HELP WILL BE HELPFUL
PhoneBook delete()
TESTER PROGRAM
class Tester
public static void main (String[] args)
EasyReader console= new EasyReader();
PhoneBook pb = new PhoneBook();
System.out.println("1-Find phone number 2-Add entry 3-Delete entry? (type 1,2 or 3 only)");
String answer= console.readLine();
if (answer.equals("1"))
          System.out.println("Last Name? ");
          String lname= console.readLine().toUpperCase();
          System.out.println("Name? ");
          String fname= console.readLine().toUpperCase();
          PhoneEntry entry = pb.search(lname, fname);
     if ( lname.equals("QUIT") || fname.equals("QUIT") )
          System.out.println( "Good-bye." );
          if ( entry != null)
          System.out.println( entry.lastname +" "+entry.firstname +":"+ entry.phone);
else if (answer.equals("2"))
          PhoneBook new_entry = new PhoneBook();
     System.out.println("Enter last name: ");
          String lastname= console.readLine();
          System.out.println("Enter name: ");
          String name = console.readLine();
          System.out.println("Enter phone number: ");
          String number = console.readLine();
          PhoneEntry entered= new_entry.add(lastname, name, number);
     if ( entered != null)
               System.out.println( "New number added = "+entered.lastname +
               " "+entered.firstname +":"+ entered.phone);
THIS IS WHERE I WANT THE DELETE METHOD TO TAKE EFFECT
     else if (answer.equals("3"))
          PhoneBook todelete = new PhoneBook();
          System.out.println("Enter lastname to be deleted");
          String del_lastname = console.readLine();
          System.out.println("Enter name to be deleted");
          String del_name = console.readLine();
          String empty="";
          //NOT SURE HOW TO MAKE IT HAPPEN THOUGH
          PhoneEntry del_entry =pb.search(del_lastname, del_name);
          System.out.println(del_last.firstname+" "+del_name.lastname+" has been deleted");
help will be greatly appreciated
thank you

This question has little to do with algorithms (this is the algorithms forum). I suggest you post your question in the general Java programming forum:
[http://forum.java.sun.com/forum.jspa?forumID=31]
Good luck.

Similar Messages

  • ToString array and equals method

    I have an array and i need to get the toString to output the information. How do I get that to happen. This is what i ahve so far.
       public String toString(){
              //should indicate all cities
              System.out.print("Cities :");
              for (int i = 0; i < cities.length -1; i++)
                   return cities;
    Here is another piece of code I am finishing. Please tell me if the loop and equals method is correct but what is the value to return?
       public City getCity(String cityName){
              //returns the City with name cityName (must search for city in the array)
              //if the city does not exist, it returns null
              for(int i = 0; i < cities.length; i++)
                   if(cityName.equals ("cityName"))
                        return ;
                    else return null;
                Message was edited by:
    ehj3000

    great my world class is fixed now im getting missing return statements on the two methods
           public City getCity (String cityName){
          //returns the City with name cityName (must search for city in the array)
          //if the city does not exist, it returns null
             for(int i = 0; i < cities.length; i++)
                if(cities.getName().equals(cityName))
    return cities[i];
    else
    return null;
    public String toString(){
    //should indicate all cities
    System.out.println("Cities: ");
    for (int i = 0; i < cities.length -1; i++)
    return cities[i].getName();

  • Is in Java have order for datatype(that is not array and collection)

    Dear Friends,
    I have a class Test{
    void Test( String name,int cnt,Test1 abc){
    this.name= name;
    this.cnt=cnt;
    this.abc=abc
    String name;
    int cnt;
    Test1 [] abc;
    in some class Test2 , I fill data into obj ( obj = new Test("siddharth",23,objtest1);
    I THING THAT WE CAN NOT SAY THE ORDER WILL BE in Object obj in this way
    First Element : siddharth
    Second Element"23
    and
    Third Element :objtest2
    but My Team Lead is saying that Object has Order according theair Hascode() value.
    Is is true Or not.
    But in my Webspare studio debugeer is shoing the order is
    First Element:objtest2
    Second Element :siddharth
    Third Element :23
    and in same way GLUE component is generating xml.
    So pls tell me how can i Change my order of element.
    Pls Help me.it is very very urgent for me
    with regards Siddharth Singh
    }

    I THING THAT WE CAN NOT SAY THE ORDER WILL BE in Object obj in this wayYou could only suggest this if you don't understand arrays. Arrays do not re-organise themslves. The array object will be in the cell you put them in. The order is entirely up to you and will not change unless you change it.
    but My Team Lead is saying that Object has Order according theair Hascode() value.This will be the order, or this needs to be the order?
    The order is the one you make it. You can change the order with the Arrays.sort() method.
    Is is true Or not.Not even close to true.
    So pls tell me how can i Change my order of element.Use Arrays.sort()

  • How to ask for an array and how to save the values

    I'm supposed to be learning the differences between a linear search and a binary search, and the assignment is to have a user input an array and search through the array for a given number using both searches. My problem is that I know how to ask them how long they want their array to be, but I don't know how to call the getArray() method to actually ask for the contents of the array.
    My code is as follows:
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Main
        private static Scanner input = new Scanner(System.in);
        public static void main (String args[])
            //creates ArrayList
            int List[];
            System.out.println("How long would you like the array to be?");
            int arrayLength = input.nextInt();
            //Initializes array list
            List = new int [arrayLength];
            System.out.println("Please enter the first value of the array");
        public static void getArray(int List[], int arrayLength)
            for(int i=0; i < arrayLength; i++) {
                 System.out.println("Enter the next value for array");
                 List[i] = input.nextInt();
         public static void printArray(int List[])
             for(int i=0; i < List.length; i++)
                 System.out.print(List[i] + " ");
    public class search
        public static int binarySearch(int anArray[], int first, int last, int value)
            int index;
            if(first > last) {
                index = -1;
            else {
                int mid = (first + last)/2;
                if(value == anArray[mid]) {
                    index = mid; //value found at anArray[mid]
                else if(value < anArray[mid]) {
                    //point X
                    index = binarySearch(anArray, first, mid-1, value);
                else {
                    //point Y
                    index = binarySearch(anArray, mid+1, last, value);
                } //end if
            } //end if
            return index;
        //Iterative linear search
        public int linearSearch(int a[], int valueToFind)
            //valueToFind is the number that will be found
            //The function returns the position of the value if found
            //The function returns -1 if valueToFind was not found
            for (int i=0; i<a.length; i++) {
                if (valueToFind == a) {
    return i;
    return -1;

    I made the changes. Two more questions.
    1.) Just for curiosity, how would I have referenced those methods (called them)?
    2.) How do I call the searches?
    import java.util.Scanner;
    import java.util.ArrayList;
    public class Main
        private static Scanner input = new Scanner(System.in);
        public static void main (String args[])
            //creates ArrayList
            int List[];
            System.out.println("How many values would you like the array to have?");
            int arrayLength = input.nextInt();
            //Initializes array list
            List = new int [arrayLength];
            //Collects the array information
            for(int i=0; i < arrayLength; i++) {
                 System.out.println("Enter a value for array");
                 List[i] = input.nextInt(); 
            //Prints the array
            System.out.print("Array: ");
            for(int i=0; i < List.length; i++)
                 System.out.print(List[i] + " ");
            //Asks for the value to be searched for
            System.out.println("What value would you like to search for?");
            int temp = input.nextInt();
            System.out.println(search.binarySearch()); //not working
    }

  • Doubt in working of Arrays.sort method. help needed !!!!

    Hello Friends,
    I am not able to understand output of Arrays.sort method. Here is the detail of problem
    I wrote one program :
    public static void main(String[] args) throws ClassNotFoundException
         Object[] a = new Object[10];
         a[0] = new String("1");
         a[1] = new String("2");
         a[2] = new String("4");
         a[3] = new String("3");
         a[4] = new String("5");
         a[5] = new String("20");
         a[6] = new String("6");
         a[7] = new String("9");
         a[8] = new String("7");
         a[9] = new String("8");
    /* Sort entire array.*/
         Arrays.sort(a);
         for (int i = 0; i < a.length; i++)
         System.out.println(a);
    and output is :
    1
    2
    20
    3
    4
    5
    6
    7
    8
    9
    Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
    Can here any one please explain this?
    Thanks in advance.
    Regards,
    Rajesh Rathod

    jverd wrote:
    "20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
    ... quote 20 quote less than quote 3 quote...
    but shows up as
    ... quote 20 quote less than quote...
    Weird.

  • Dynamically create empty mcs and asign elements from array and loadmovie

    I'm creating an educational game for my school students.
    A little boy is flying through the city when he encounters objects flying from left to right.
    He hears a SOUND eg: Dog - he must go and click the dog image with the flying cursor. There are at least 5 DIFFERENT objects that should be flying on the screen. There could be various of them at any one time.
    I have the roots of the images in an xml file. And the actual swf are in a file called IMAGE and the sounds in SOUND.
    My problem is that most tutorials I see use the attachmovie method but I don't want to put all the swf's in the library as there are hundreds.
    I have to use the loadmovie method.
    I take it I have to loop through the array and assign each element to an empty movieclip which in turn is in the loop so you get 5 empty clips - I will use i (index). It doesn't seem to be working. I shall keep trying and post back here if I get any luck but I'm running out of ideas.
    Then the objects have to float across the screen. Don't know whether to use tween object or onEnterFrame handler or other. AND someone has mentioned using setinterval to "spit out" the objects.
    BUT if I have five flying across the screen I'm left without clips to stick in any more.
    Oh my head hurts but I will keep going.
    CHEERS if any help is around. This should be quite a standard thng for game developpers. Code at the moment
    function loadEnemies():Void {
    enemy_xml = new XML();
    enemy_xml.ignoreWhite = true;
    enemy_xml.onLoad = function(success:Boolean) {
    if (success) {
    _root.parseEnemyXML();
    //enemy_xml.load("level_"+level+".xml");
    enemy_xml.load("data/animal_catch.xml");
    function parseEnemyXML():Void {
    rows = enemy_xml.firstChild.childNodes.length;
    for (var i:Number = 0; i<rows; i++) {
    var row_string:String = String(enemy_xml.firstChild.childNodes[i].firstChild.firstChild);
    _root["row_"+i+"_array"] = row_string; //MAIN ARRAY holds an array images/dog_a.swf/ images/cat_a.swf etc... all five
    _root.createEmptyMovieClip("enemyObjects", 1);
    enemyObjects.createEmptyMovieClip("holder_"+i, i);
    _root["object"+i] = new Sound(enemyObjects["holder_"+i]);
    trace(row_string);
    loadMovie["row_"+i+"_array"], ["holder_"+i]
    if (level == 1) {
    alerts_mc.play();
    } else {
    currRow = 0;
    rowCounter = 0;
    OK got to about here BUT
    a. I started to get confused around the createEmptyMovieClip part
    b. I KNOW I shouldn't have Sound(enemyObjetcs etc... BUT I copied the code from a tutorial and I don't know what to replace it with.
    I'm close but I need a little polishing.

    It doesn't do you much good to work with borrowed code that you do not understand.  Your best bet will be to start small, creating one functional piece of the puzzle at a time, and work your way up.  Start with making sure you are loading and parsing the xml properly, then set about loading the external content, then see about making that content move around, etc...
    In the code you show, your loadMovie line of code does not resemble anything I have seen before, looking more like (but not quite like) a multi-dimensional array element than a loadMovie() function call.  If you find you need to have control of the items as soon as they load, then you should consider using MovieClipLoader.loadClip instead of loadMovie.  The MovieClipLoader class provides features, such as to be able to determine when items have fully loaded.

  • Inserting Records in an Array and using a constructor with it

    I badly need help on this! Please please please! I have been studying java for a short time only.
    Anyway, here goes: My project requires the following:
    Employee inputs the no. of video in the shelf. They have four classifications: Drama, Comedy, Action, and Thriller. Each video classification has different rates. The employee creates a video record containing the following information: 1. video ID number, 2. video classification, and 3. Price.
    The employee should display the classifications of videos available and the price. Only the available video tapes would be displayed according to the customer's chosen classification. When the customer chooses the video he wants to rent, the program will register and attach the name of the customer to the video number.
    I only need to use arrays, and NOT database to record the information.

    is it ok i i declare the drama_rate outside the video class?
    i have a list of variables on my videoupdate classYes. It's probably best to declare it static & then you can access it directly:
    public static float drama_rate = 100.0;
    rate = <the class name>.drama_rate;
    so, i should also include a customer no. both in the video and customer class.I would. You may want to list a bunch of videos and who currently has them. This way you don't have to search the customers AND the videos to do this.
    thanks =) i don't know either why we had to validate/invalidate,\
    but our applet doesnt refresh when >it is supposed to, so
    we just used this method. It wouldnt slow down the application, would it?Could you just revalidate()?
    the use of arrays. i havent finished with the program yet.
    i have the design already, i just couldnt put it in code.
    im not familiar with the use of multidimensional arrays-
    can i use this for the video and customer records i will need to store?Not sure what you're using arrays for, but here's an example of something I might do. Maybe it will be useful to you.
    Have you looked at HashMaps? You could use "Customer" as the key and then use an ArrayList of checked out Videos as the value:
    HashMap customers = new HashMap();
    ArrayList videos = new ArrayList();
    //Add the checked out videos to the list
    videos.add(video);
    <etc>
    // Add this customer and the list of videos he has checked out.
    customers.put(customer,videos);
    [\code]

  • Excel & ActiveX: Insert arbitrary columns from 2D array and create graph problems

    Hi there,
    I want to insert data from either a 1D or 2D array from LabView into Excel and create graphs.
    I used the information from the following example:
    http://www.ni.com/example/28934/en/
    and was able to create a new Excel file (I'm using Excel 2010), writing data from an 1D array to a column in excel by creating a while loop and using the first element of the array to write it to a specific cell. I use the counter of the loop to write to the next cell when the loop starts over and always delete the first value, which I write to the cell, from the array until it is empty.
    Now I also would like to write a 2D array - so the first column in Excel should be the first column from the array and so. Here I cannot use the loop counter directly as Excel only counts 1,2,... for the rows, but uses A,B,... to count columns. Also I do not know in advance how many columns my 2D array will contain, so creating a lookup table like (A means 1, B means 2,...) is not really an option (except there really is no other way). Is there a possibilty to convert numbers into letters or some way to 'explain' to the program that column 2 in the array means column B in Excel for example, or is there a way to insert new columns?
    I figured out how to add new Worksheets and as I also need to create a certain number of Worksheets and I know that on standard 3 sheets are present when creating the file, I use the 'add' methode to create every new worksheets before worksheet 3 - I could use the same methode to create new columns in Excel, but so far I didn't find a methode to do so. Or is there a way to enter the whole 2D array at once?
    Then I'd like to create a graph (in case of the 1D arrays a bar plot, when using 2D arrays a 3D plot) to view the data. I found this example:
    http://www.ni.com/newsletter/51339/en/
    -> as I do not have the toolkit I'd like to do it using ActiveX directly, so I tried to do things like shown under the headline 'DIY ActiveX/.NET'
    I tried to load the snippet to a new Excel file but got the error message 'microsoft.office.interop.excel.dll not found' and hence the code is not working. That confuses me a little as I would guess when this dll is not present I cannot access Excel from LabView at all, though my understanding of what I'm really doing so far is quiet limited. ;-)
    Also - as far as I understand from the snippet - when creating a new chart object I should be able the create methodes for it, however when I do a right click on the chart object of an ActiveX Worksheet symbol there are none listed.
    To explain my problems better I added a snippet showing my two problems: The inner of the two while loops shows how I import a 1D array. In the outer loop I seperate the columns. I know that currently this is not working as all data end up in column A of the Excel sheet - so I would need to convert the number of the outer counter to A, B,... or find a different solution.
    Moreover on the snippet I placed an ActiveX Worksheet Property with the Chart Object - as I can see the difference to the Chart Object in the example code from the last link above is the color. However I'm not sure what that means and how to change/ solve this.
    And just to make sure - I know this way the VI does not run as the Chart Object is placed completely wrong - I just did it, so it is included in the snippet.
    I'd be thankful for any suggestions,
    Thanks!
    Solved!
    Go to Solution.
    Attachments:
    ExcelAreaScan.png ‏60 KB

    Hello everyone and thanks for the answers.
    I only have the LabView Student Edition available here - is the toolkit included in it too. How can I check if it is installed/ available and in case it is installed - where can I find it?
    Today I had time to take a look at the example
    Create via ActiveX Labview a XY Scatter plot graph on an excel sheet
    It almost does what I want in terms of creating a graph. The only problem I could not fix, is that in this example a sheet is created where only the graph is present. i'd like to add the graph to a previously created worksheet. Today I tried get this working but it seems I stilll don't really understand what I'm doing, I'll post a snippet of my code as soon as I can access the PC with LabView on it again.
    I also took a look at the other example for inserting 2D attays - it seems to be what I need, I just had no time so far to test it, I'll post an update when I could test it.
    Thanks for the help so far!

  • Trouble with primitive arrays and casting, lesson 521

    hi everyone!
    there is a problem i discovered right now - after years with java where was no necessity to do this.....
    and i'm shure this must have been the topic already, but i couldn't find any helpful resource :-/
    right here we go:
    1. an array is a (special) kind of object.
    2. there are "primitive" arrays and such containing references to objects. of course - and i imagine why - they are treated differently by the VM.
    3. then both are - somehow - subclasses of Object. whereas primitive types are not really, primitive-arrays are. this is hidden to the programmer....
    4. any array can be "pointed" at via local Object variable, like this:
    Object xyz = new int[6];
    5. arrays of Objects (with different dimensions) can be casted, like this:
      Object pointer = null;
      Object[]   o  = new SomeClass[42] ;
      Object[][] oo = new OtherClass[23] [2] ;
      Object[][][] ooo = new OtherClass[23] [2] [9] ;
      o = oo = ooo;     // this is save to do,
                                   //because "n-dimensional" object-arrays
                                  // are just arrays of  other arrays, down to simple array
    pointer = o;         // ok, we are referencing o via Object "pointer"6. but, you cannot do this with primitive types:
      int[]  i1 = new int [99] ;
      int[][] i2 = new int [1] [3] ;
      i1 = i2                  // terror: impossible. this is awful, if you ask me.
                                   // ok, one could talk about "special cases" and
                                   // "the way the VM works", but this is not of interest to me as
                                   // a programmer. i'm not happy with that array-mess!
      pointer = i2;       // now this is completely legal. i2, i1 etc is an object!7. after the preparation, let's get into my main trouble (you have the answer, i know!) :
    suppose i have a class, with methods that should process ANY kind of object given. and - i don't know which. i only get it at runtime from an unknown source.
    let's say: public void BlackBox( Object x );
    inside, i know that there might be regular objects or arrays, and for this case i have some special hidden method, just for arrays... now try to find it out:
    public void BlackBox( Object x )
      if ( x == null)
           return;
       Class c = x.getClass();
       if ( c.isArray() )
              // call the array method if it's an array.........
              BlackBoxes(     (Object [] )  x );         // wait: this is a cast! and it WILL throw an exception, eventually!
              return;
       else
               DoSpecialStuffWith( x );
    }ok ? now, to process any kind of array, the special method you cannot reach from outside:
    private void BlackBoxes( Object[] xs )
       if ( xs != null )
            for ( Object x : xs )
                 BlackBox( x );
    // this will end up in some kind of recursion with more than one array-dimension, or when an Object[] has any other array as element!this approach is perfectly save when processing any (real) Object, array or "multi-dimensional" arrays of Objects.
    but, you cannot use this with primitive type arrays.
    using generics wouldn't help, because internally it is all downcasted to Object.
    BlackBox( new Integer(3) ) ---- does work, using a wrapper class
    BlackBox( new Integer[3] ) ----- yep!
    BlackBox( 3 ) ---- even this!
    BlackBox( new int[42] ) ---- bang! ClassCastException, Object[] != int[]
    i'm stuck. i see no way to do this smoothly. i could write thousands of methods for each primitive array - BlackBox( int[] is ) etc. - but this wouldn't help. because i can't cast an int[][] to int[], i would also have to write countless methods for each dimension. and guess, how much there are?
    suppose, i ultimately wrote thousands of possible primitive-type methods. it would be easy to undergo any of it, writing this:
    BlackBox( (Object) new int[9] [9] );
    the method-signature would again only fit to my first method, so the whole work is useless. i CAN cast an int[] to Object, but there seems no convenient way to get the real array out of Object - in a generic way.
    i wonder, how do you write a serialisation-engine? and NO, i can't rely on "right usage" of my classes, i must assume the worst case...
    any help appreciated!

    thanks, brigand!
    your code looks weird to me g and i think there's at least one false assumption: .length of a multidimensional array returns only the number of "top-level" subarrays. that means, every length of every subarray may vary. ;)
    well i guess i figured it out, in some way:
    an int is no Object;
    int[ ] is an Object
    the ComponentType of int [ ] is int
    so, the ComponentType of an Object int[ ] is no Object, thus it cannot be casted to Object.
    but the ComponentType of int [ ] [ ] IS Object, because it is int [ ] !
    so every method which expects Object[], will work fine with int[ ] [ ] !!
    now, you only need special treatment for 1-dimensional primitive arrays:
    i wrote some code, which prints me everything of everything:
        //this method generates tabs for indentation
        static String Pre( int depth)
             StringBuilder pre = new StringBuilder();
             for ( int i = 0; i < depth; i++)
                  pre.append( "\t" );
             return pre.toString();
        //top-level acces for any Object
        static void Print( Object t)
             Print ( t, 0);
        //the same, but with indentation depth
        static void Print( Object t, int depth)
            if ( t != null )
                 //be shure it is treated exactly as the class it represents, not any downcast
                 t = t.getClass().cast( t );
                if ( t.getClass().isArray() )
                     //special treatment for int[]
                     if ( t instanceof int[])
                          Print( (int[]) t, depth);
                     // everything else can be Object[] !
                     else
                          Print( (Object[]) t, depth );
                     return;
                else
                    System.out.println( Pre(depth) + " [ single object:] " + t.toString() );
            else
                System.out.println( Pre(depth) + "[null!]");
        // now top-level print for any array of Objects
        static void Print( Object [] o)
             Print( o, 0 );
        // the same with indentation
        static void Print( Object [] o, int depth)
            System.out.println( Pre(depth) + "array object " + o.toString() );
            for ( Object so : o )
                    Print( so, depth + 1 );
        //the last 2 methods are only for int[] !
        static void Print( int[] is)
             Print( is, 0 );
        static void Print( int[] is, int depth)
            System.out.println( Pre(depth) + "primitive array object " + is.toString() );
            // use the same one-Object method as every other Object!
            for ( int i : is)
                 Print ( i, depth + 1 );
            System.out.println( "-----------------------------" );
        }now, calling it with
    Print ( (int) 4 );
    Print ( new int[] {1,2,3} );
    Print( new int[][] {{1,2,3}, {4,5,6}} );
    Print( new int[][][] {{{1,2,3}, {4,5,6}} , {{7,8,9}, {10,11,12}}, {{13,14,15}, {16,17,18}} } );
    Print( (Object) (new int[][][][] {{{{99}}}} ) );
    produces this fine array-tree:
    [ single object:] 4
    primitive array object [I@9cab16
          [ single object:] 1
          [ single object:] 2
          [ single object:] 3
    array object [[I@1a46e30
         primitive array object [I@3e25a5
               [ single object:] 1
               [ single object:] 2
               [ single object:] 3
         primitive array object [I@19821f
               [ single object:] 4
               [ single object:] 5
               [ single object:] 6
    array object [[[I@addbf1
         array object [[I@42e816
              primitive array object [I@9304b1
                    [ single object:] 1
                    [ single object:] 2
                    [ single object:] 3
              primitive array object [I@190d11
                    [ single object:] 4
                    [ single object:] 5
                    [ single object:] 6
         array object [[I@a90653
              primitive array object [I@de6ced
                    [ single object:] 7
                    [ single object:] 8
                    [ single object:] 9
              primitive array object [I@c17164
                    [ single object:] 10
                    [ single object:] 11
                    [ single object:] 12
         array object [[I@1fb8ee3
              primitive array object [I@61de33
                    [ single object:] 13
                    [ single object:] 14
                    [ single object:] 15
              primitive array object [I@14318bb
                    [ single object:] 16
                    [ single object:] 17
                    [ single object:] 18
    array object [[[[I@ca0b6
         array object [[[I@10b30a7
              array object [[I@1a758cb
                   primitive array object [I@1b67f74
                         [ single object:] 99
    -----------------------------and i'll have to write 8 methods or so for every primitive[ ] type !
    sounds like a manageable effort... ;-)

  • Passing array as method to activex

    Dear Users;
    Sorry if this is a repeat question - I could not find relevant code in the faq.
    I have an activeX control which contains a method (PassArray) which accepts an array, and modifies its contents... The array *seems* to be correctly passed in, and I can make the modifications to the data. The data is then passed back out... In labview I use the Variant -> Data object to return the underlying dataset. However all my modifications are lost. (Sample code below).
    Ie: it seems Labview is passing me a copy of the original data, and does not accept that changes have occured. When I create a method which returns a variant containing a new array (ReturnArray), everything works properly. Does this occur because methods use 'const' keywords for parameters? Is there a solution where labview accepts that the data has changed?
    Any hints would be useful...
    thanks,
    Marc
    VARIANT CAcxLVArrayCtrl::ReturnArray(short Lendth)
    VARIANT vaResult;
    VariantInit(&vaResult);
    // TODO: Add your dispatch handler code here
    // Ok use this code to generate an array based upon size of Lendth.
    double* lpusBuffer;
    //Assigns the Variant to hold an array of doubles (real 8-byte numbers)
    vaResult.vt = VT_ARRAY | VT_R8;
    SAFEARRAYBOUND rgsabound[1];
    //Set bounds of array
    rgsabound[0].lLbound = 0; //Lower bound
    rgsabound[0].cElements = Lendth; //Number of elements
    //Create the safe array of doubles, with the specified bounds, and only 1 dimension
    vaResult.parray = SafeArrayCreate( VT_R8, 1, rgsabound );
    SafeArrayAllocData( vaResult.parray );
    SafeArrayAccessData( vaResult.parray, (void**)&lpusBuffer );
    //Fill in the buffer
    for( int i=0; i
    *(lpusBuffer + i ) = i + 1;
    SafeArrayUnaccessData( vaResult.parray );
    return vaResult;
    short CAcxLVArrayCtrl:assArray(const VARIANT FAR& ArrayInOut)
    // TODO: Add your dispatch handler code here
    long LowerBound, UpperBound, cbElements;
    if(ArrayInOut.vt != (VT_ARRAY | VT_I4))
    MessageBox("Data is not an array of Longs");
    return -1;
    if(SafeArrayGetDim(ArrayInOut.parray) != 1)
    MessageBox("Data must be a 1D array");
    return -1;
    SafeArrayGetLBound(ArrayInOut.parray, 1, &LowerBound);
    SafeArrayGetUBound(ArrayInOut.parray, 1, &UpperBound);
    if( (UpperBound - LowerBound) = 0)
    MessageBox("Data array is not initialised");
    return -1;
    long* lpusBuffer;
    SafeArrayAccessData( ArrayInOut.parray, (void**)&lpusBuffer );
    //Fill in the buffer
    for( int i=LowerBound; i
    *(lpusBuffer + i ) = i + 1;
    SafeArrayUnaccessData( ArrayInOut.parray );
    return 0;

    Fortunately I was able to determine what I was doing wrong. LabView and Visual Basic for Applications (VBA) only support the VARIANT data type for arrays. Visual Basic, however, supports more descriptive array parameter specifications in IDL. In other words, there are numerous valid ways to declare array parameters in IDL, however, some tools only support a subset. LV only supports VARIANTs. So in the previous IDL example:
    [id(3), helpstring("method NSEnumDevice")] HRESULT NSEnumDevice([in] int devIndex, [in] SAFEARRAY(int) *ports);
    becomes -
    [id(3), helpstring("method NSEnumDevice")] HRESULT NSEnumDevice([in] int devIndex, [in] VARIANT ports, [out, retval] VARIANT *devObj);
    Where devObj is an ActiveX wrapped object. VARIANT "ports" is an array of integer values. To specify returning an array of values, you still just use "[out, retval] VARIANT *array".
    --ddixon

  • Accessing array content methods

    This is quite simple to do in C++ from what I remember but its got me stumped so far (it is getting late so maybe my brains slowing down).
    I simply want to access an object in my array and use its getValue() function to return the value of that object.
    Unfortunately I can't seem to do it at the moment.
    I presumed i'd be able to do something like MyArray.get(1).getValue.
    Basically im looking for the Java version of MyArray[1].getValue()
    Sorry to bother you with such a simple question but the search archive had posts focusing on accessing classes from other classes/packages.
    Thanks

    jverd,
    I haven't set my array to specifically store a
    specific object, however I know it always will.
    Are you suggesting there is a better way?Declare the type to be as specific as you can.
    If you're only sticking Foo objects in there, declare it as Foo[]. If you're sticking Foo and Bar objects in there, but the have a common superclass or implement a common interface Baz, then declare it as Baz[]. BUT only if you want to use the objects as Bazes. If you're going to have to cast it to Foo or to Bar because you want to access methods that only those classes have--that aren't in Baz--then you probably shouldn't be storing them in the same array.
    Storing a single type is also a good idea with Collections. However up through 1.4, you can't declare the type that the collection will hold. With 1.5, generics lets you do that.

  • Cloning an array and reflection magic

    * Arrays support cloning. But why is not possible to fetch an
    * arrays clone()-method using reflection? Or is it anyway?
    * Please watch out for the calls to getMethod() and clone()
    * in this class' main()-method. Perhaps I missed something. Thank you!
    import java.lang.reflect.Method;
    public class Question {
    public static void main (String[] args) {
    Object[] array = new Object[5];
    try {
    Class c = array.getClass();
    //! throwing a NoSuchMethodException!
    Method m = c.getMethod("clone", null);
    m.invoke(array, null);
    } catch (Exception e) {
    e.printStackTrace();
    // but this is works properly:
    array.clone();
    }

    // ...and now I've discovered the -tag...
    import java.lang.reflect.Method;
    public class Question {
    public static void main (String[] args) {
    Object[] array = new Object[5];
    // throwing a NoSuchMethodException!
    try {
    Class c = array.getClass();
    Method m = c.getMethod("clone", null);
    m.invoke(array, null);
    } catch (Exception e) {
    e.printStackTrace();
    // but this is o.k.
    array.clone();

  • Track public classes, interfaces and methods by ID

    Hi All,
    I'm wondering whether there is a tool to assign a unique ID to classes, interfaces and methods (eg. within Javadoc) and track these IDs.
    The reason I'd need such a feature is that I'd like to do requirements tracking in an easy but complete way. I have a document containing functional specifications (with IDs) and on the other side there is the source code; where the javadoc of the public methods and classes is my software specification. What I now want to do is make a link between the IDs in the functional spec to the IDs in the sofware spec (ie. the source code).
    Does anybody know of such a tool (commercial or not)?
    Thanks,
    Daniel

    I'm a bit confused as to whether or not I understand you correctly. Please tell me if the following pseudocode is somewhat like the solution you are looking for:
    class MethodFunctionality {
       private Class methodClass;
       private String methodSignature;
       private List methodFunctions;
        *   Returns true if the method is used for the specified
        *   requirement, false otherwise.
       public boolean fulfills(int requirementId) {
          if methodFunctions.contains(requirementId)
             return true;
          else
             return false;
       public String getMethodSignature() {
          return this.methodSingature;
       public Class getMethodClass() {
          return this.methodClass;
        *   Returns an array with IDs of each functional
        *   requirement covered by the method.
       public int[] getCoverage() {
          return this.methodFunctions;
    class ClassFunctionality {
       private Map methodDetails;
       private List classFunctions;
       public MethodFunctionality getMethodDetails(String methodSignature) {
          return (MethodFunctionality) this.methodDetails.get(methodSignature);
        *   Returns true if the class is used for the specified
        *   requirement, false otherwise.
       public boolean fulfills(int requirementId) {
          if classFunctions.contains(requirementId)
             return true;
          else
             return false;
        *   Returns an array with IDs of each functional
        *   requirement covered by the class.
       public int[] getCoverage() {
          return this.classFunctions;
    }Mapping classes and methods to functionality like this would both allow you to query each class and method for all the functional requirements they claim to cover and would allow you to collect all classes and methods involved for a particular functional requirement.

  • Trying to pass parameters between GUI classes and methods

    Hi All.
    I have been working on a rather large final year project in college and it is getting close to the deadline. It looks as though I need to "tidy up" my code as it contains too many static methods, variables and other bad programming habits. My package consists of many different GUI's and classes. Up until now I have been calling different GUI's with guiName.NameOfMethod. I have been told this is bad practice so I am trying to fix this. Also instead of passing parameters correctly I have been creating static variables in my main class and using them. So for example if one class needed to pass a variable to the other I would first myGlobalVariable = X; in the first class. And then the second class can use this. This is also bad, right?
    So I guess im really just looking for a good example or tutorial on how to pass parameters between classes and methods, GUI if possible. Here is an example of how my GUI classes look:
    public class anotherGUI extends JFrame implements ActionListener {
            private JTextField a, b, c;
            private JButton button1, button2;
            JPanel p, p1;                   
            public anotherGUI() {
                LayOutAnotherGUI();
                setLocationRelativeTo(DnDMain.pictureArray[a]);
                setTitle("Example");
                setVisible(true);
                pack();     
            private void LayOutAnotherGUI(int c) {
         //GUI is layed out here     
            public void actionPerformed(ActionEvent e) {
                Object source = e.getSource();
                if (source == submit)
                    clickOK();
            public void clickOK(){
                //Here is where I have been accessing and modifying static global variables.  (But this needs to change).
    public void showanotherGUI() {
            new anotherGUI();
    }This is more or less how I have been going about creating my GUI's. These are used as pop ups. The user enters a value and then it is closed.
    To be honest I have been able to pass a variable correctly from one class to a GUI class but I have still having difficulty. For example in my code above I can pass the variable into this class but I cannot pass it into clickOK(). An this is where it is needed.
    Can anyone please help?
    I hope I have explained my problem well.
    Thanks in advance.

    I dont think that is what I need. An example of what I do in my program is:
    I have a main GUI with an array of images. There are a number of other small GUI's that appear for certain functions when the user clicks on an image or does some other function. I am trying to pass a value into the GUI class that is used for the smaller "pop up" GUI. So lets say the user has clicked the image in array[12]. Then a GUI is displayed. I need to pass the integer 12 into this class.
    Thanks.

  • Weblogic 10.3 - Arrays and JAX-RPC Web Services

    We are currently looking at migrating from WL 8.1 to WL 10.3, and have an issue with some of our web services (JAX-RPC) with regards to returning String arrays.
    We have a web service method that returns a response object. This response object has many properties that includes a property that is a String array. So the code looks something like this (this is a simplified version):
    <em>public class OurService
    @RemoteMethod
    @WebMethod
    @WebResult(name = "result")
    public ResponseObject lookup(String someParam)
    // build the object and its properties here...
    return responseObject;
    }</em>
    This is what the response object looks like:
    <em>public class ResponseObject
    private String[] someProperty;
    public String[] getSomeProperty()
    return this.</em><em>someProperty</em><em>;
    public void setSomeProperty(String[] </em><em>someProperty</em><em>)
    this.</em><em>someProperty</em><em>= </em><em>someProperty</em><em>;
    }</em>
    So the issue is this. In WL 8.1, the web service generator would recognise the fact that the response object had a property that was a String array and would declare as such in the WSDL file, for example:
    <em><strong> &lt;xsd:element xmlns:tp="java:language_builtins.lang" type="<font color="#ff0000">tp:ArrayOfString</font>" name="someProperty" minOccurs="1" nillable="true" maxOccurs="1"&gt;
    &lt;/xsd:element&gt;
    </strong></em>
    As a result, when the service is called, the property is returned in the SOAP response like this:
    <strong>.
    </strong>
    <div class="e">
    <div class="c" style="margin-left: 1em; text-indent: -2em">
    <em><strong> <span class="m">&lt;</span><span class="t">someProperty</span><span class="t"> soapenc:arrayType</span><span class="m">="</span></strong><strong>xsd:string[2]<span class="m">"</span><span class="m">&gt;</span></strong></em>
    </div>
    <div>
    <div class="e">
    <div>
    <em><strong><span class="b"> </span><span class="m">&lt;</span><span class="t">string</span><span class="t">
    xsi:type</span><span class="m">="</span></strong><strong>xsd:string<span class="m">"</span><span class="m">&gt;</span><span class="tx">string1</span><span class="m">&lt;/</span><span class="t">string</span><span class="b">&gt;
    &lt;string xsi:type="xsd:string"&gt;string2&lt;/string&gt;
    </span><span class="m">&lt;/</span><span class="t">someProperty</span><span class="m">&gt;</span></strong></em>
    </div>
    </div>
    </div>
    </div>
    <strong>.
    </strong>
    But, in WL 10.3, the WSDL entry is:
    <em><strong> &lt;xs:element maxOccurs="unbounded" minOccurs="0" name="InstepCodes" nillable="true" type="xs:string"&gt;
    </strong></em>
    As a result the property is returned in the SOAP response like this:
    <strong> .
    </strong><strong><span class="m"> &lt;</span><span class="t">java:InstepCodes</span><span class="ns">
    xmlns:java</span><span class="m">="</span></strong><strong class="ns">java:com.myservice</strong><strong><span class="m">"</span><span class="m">&gt;</span><span class="tx">string1</span><span class="m">&lt;/</span><span class="t">java:InstepCodes</span><span class="m">&gt;</span>
    </strong><strong><span class="m"> &lt;</span><span class="t">java:InstepCodes</span><span class="ns">
    xmlns:java</span><span class="m">="</span></strong><strong class="ns">java:com.myservice</strong><strong><span class="m">"</span><span class="m">&gt;</span><span class="tx">string2</span><span class="m">&lt;/</span><span class="t">java:InstepCodes</span><span class="m">&gt;</span>
    </strong>The difference here is that WL 10.3 does not return the array of strings as a complex array type, just as a set of repeated elements.
    We need to return the array as we do for WL 8 in WL 10.3, because we have external clients that are parsing the response and looking for the XML in this format. We are not currently in a position to ask them to change.
    Is this a limitation of the JAX-RPC spec, or WL's implementation of it?
    If the service was to return a String array directly from a service method, then it is declared in the WSDL file.
    However, if a service returns an object that within itself has a property that is an array, it does not recognise it like it did with WL 8.1.
    <strong>
    </strong>
    <div class="e">
    </div>

    Thank you for the reply.
    We are using WL Server 8.1 (not Workshop), and moving to WL Server 10g R3.
    We are using the JWSC task to generate the service, which is:
    bq. weblogic.wsee.tools.anttasks.JwscTask+
    Here is an extract from the Ant build file the calls the task.
    &lt;jwsc
    srcdir="src/com/ourservice"
    sourcepath="src"
    destdir="${ear.dir}"
    verbose="false"
    debug="true"
    keepGenerated="true"
    classpathref="ws.class.path"&gt;
    +&lt;module name="${service.name}" explode="true"&gt;+
    +&lt;jws file="OurService.java" type="JAXRPC"/&gt;+
    +&lt;/module&gt;+
    +&lt;/jwsc&gt;+
    As stated in my first post, the service method returns an reponse object and its this that contains the array property. The service method itself does not return an array type. This seems to be the root of the problem, i.e. the declaration of array types is not being propagated down through the object graph the service method returns. Below is the code for the service and the response object.
    @FileGeneration(remoteClass = Constants.Bool.TRUE, remoteClassName = "OurService", localHome = Constants.Bool.TRUE, localHomeName = "OurServiceLocalHome", remoteHome = Constants.Bool.TRUE, remoteHomeName = "++OurService++Home", localClass = Constants.Bool.TRUE, localClassName = "++OurService++Local")+
    @JndiName(remote = "com.ourservice.++OurService++", local = "com.ourservice.++OurService++Local")+
    @Session(ejbName = "++OurService++", type = Session.SessionType.STATELESS, transactionType = Session.SessionTransactionType.CONTAINER, maxBeansInFreePool = "100", initialBeansInFreePool = "20", enableCallByReference = Constants.Bool.TRUE, homeIsClusterable = Constants.Bool.TRUE, homeLoadAlgorithm = Constants.HomeLoadAlgorithm.ROUND_ROBIN, isClusterable = Constants.Bool.TRUE, beanLoadAlgorithm = "RoundRobin", defaultTransaction = Constants.TransactionAttribute.SUPPORTS)+
    +@RoleMappings( { @RoleMapping(roleName = "Admin", externallyDefined = Constants.Bool.TRUE),+
    +@RoleMapping(roleName = "Monitor", externallyDefined = Constants.Bool.TRUE),+
    +@RoleMapping(roleName = "JMS", externallyDefined = Constants.Bool.TRUE) })+
    @WebService(name = "OurServicePort", serviceName = "OurService", targetNamespace = "http://www.ourservice.com/SOA/OurService+_service")+
    +@SOAPBinding(style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL)+
    @WLHttpTransport(contextPath = "OurService", serviceUri = "OurService", portName = "
    *OurService+Port")+
    public class OurService
    +{+
    @RemoteMethod
    @WebMethod
    @WebResult(name = "result")
    {color:#ff0000}public ResponseObject lookup(String someParam){color}
    // build the response object...
    return {color:#ff0000}responseObject{color};
    +}+
    This is what the response object looks like:
    public class ResponseObject
    +{+
    private String[] someProperty;
    +public {color:#ff0000}String[] getSomeProperty(){color}+
    +{+
    return this.someProperty;
    +}+
    public void setSomeProperty(String[] someProperty)
    +{+
    this.someProperty = someProperty;
    +}+
    +}+
    From all of this I cant tell how we get the WSDL file to delcare it as an array type, as shown in the JAX-RPC 1.1 spec you mentioned, based on the code we have and the JWSC build task we are using.
    (I appologise for the formatting of this message. It seems to want to insert + everywhere in the code examples, despite me removing them!)
    Edited by: user8013492 on 11-Dec-2008 02:09
    Edited by: user8013492 on 11-Dec-2008 02:11

Maybe you are looking for