Using array to store objects

i seen array storing many integers, strings, char. but how to use array to store objects of a class..
how to define those objects created from a defined class in a array. how to obtain each instance variable of the object stored in the array.
maybe can use a student class to illustrate.

i got yr idea man!!
so whenever the compiler see
String s = "Hola Mundo";
it is simply equal to String s = new String("Hola
Mundo");
that why we can directly access value to array[0]=
"hi";
array[0]=new Student();
array[0].setName = "Hola Mundo"
is also similar in certain way to
array[0]= new String("Hola Mundo");
i right again this time?Nope waaaay off.
If Name is public in Student then it would be:
array[0].name = "Hola Mundo";
if name is private and you have a public setter setName(String newName) then it would be:
array[0].setName("Hola Mundo");
and if array is an array of strings, then array[0] = "Hola Mundo";
is correct.
PS: you still need to read the tutorials. I am out now.

Similar Messages

  • How do i use array to store a readfile information?

    currently i m facing with this problem, i have a set of .txt file data which look like below:
    6 6 3 10 3 5
    6 8 4 10 8 6
    10 17 1 11 1 1
    7 18 3 10 3 5
    8 19 1 11 1 1
    10 20 2 11 1 5
    7 20 4 10 8 6
    8 22 2 11 1 5
    10 25 4 10 8 6
    10 26 7 11 1 8
    8 27 8 12 1 11
    8 28 7 11 1 8
    10 30 9 9 8 11
    8 31 11 12 3 12
    10 32 10 11 1 12
    now i'm using while ((text = in.readLine()) != null) to read this set of data.
    how do i can store this set of data into array form as below??
    int [ ][ ] data = new String [100][6];
    //6 6 3 10 3 5 1st row
    data[0][0] = ( "6" );
    data[0][1] = ( "6" );
    data[0][2] = ( "3" );
    data[0][3] = ( "10" );
    data[0][4] = ( "3" );
    data[0][5] = ( "5" );
    //6 8 4 10 8 6 2nd row
    data[1][0]= ("6");
    data[1][1]= ("8");
    data[1][2] = ( "4" );
    data[1][3]= ("10");
    data[1][4]= ("8");
    data[1][5] = ( "6" );

    Well using the String.split() method you may be able to turn each line into an array of String numbers. So if you want an array of integers, you'll need to convert each index with Integer.parseInt().

  • Using Arrays in custom objects

    All,
    I have searched for an answer to this but have not been able to find out so I'll post the issue and see what happens.
    I am creating a service and client for use with a JavaCard system. We have a pre-existing domain class called CardMetaData wich holds information about a card such as it's type, it's name, and an array of strings representing the static keys required to create a secure channel to the card. Essentially it looks like this:
    public class CardMetaData implements Serializable
            String[] cardStaticKeys = {"key1","key2","key3");
            String name;
            String type;
            ///getters and setters..
            //plus
            public String getStaticKey(int keyType)
              return this.cardStaticKeys[keyType];
         public void setCardStaticKey(String keyValue, int keyType)
              //Validation of input may be added later or put in an Aspect
              this.cardStaticKeys[keyType]=keyValue;
    }This is a datat transfer object.
    It is served up by a service with the following interface:
    public interface JCTemplateService extends Remote
         public CardMetaData getTemplate(String ATR) throws java.rmi.RemoteException;
    }Everything compiles and deploys find. The WSDL is:
    <definitions name="JCCardTemplateService" targetNamespace="urn:JCCardTemplateService">
         <types>
         <schema targetNamespace="urn:JCCardTemplateService">
    <import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
         <complexType name="CardTemplate">
         <sequence>
    <element name="cardStaticKeys" type="tns:ArrayOfstring"/>
    <element name="description" type="string"/>
    <element name="name" type="string"/>
    </sequence>
    </complexType>
         <complexType name="ArrayOfstring">
         <complexContent>
         <restriction base="soap11-enc:Array">
    <attribute ref="soap11-enc:arrayType" wsdl:arrayType="string[]"/>
    </restriction>
    </complexContent>
    </complexType>
    </schema>
    </types>
         <message name="JCTemplateService_getTemplate">
    <part name="String_1" type="xsd:string"/>
    </message>
         <message name="JCTemplateService_getTemplateResponse">
    <part name="result" type="tns:CardTemplate"/>
    </message>
         <portType name="JCTemplateService">
         <operation name="getTemplate" parameterOrder="String_1">
    <input message="tns:JCTemplateService_getTemplate"/>
    <output message="tns:JCTemplateService_getTemplateResponse"/>
    </operation>
    </portType>
         <binding name="JCTemplateServiceBinding" type="tns:JCTemplateService">
         <operation name="getTemplate">
         <input>
    <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" use="encoded" namespace="urn:JCCardTemplateService"/>
    </input>
         <output>
    <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" use="encoded" namespace="urn:JCCardTemplateService"/>
    </output>
    <soap:operation soapAction=""/>
    </operation>
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
    </binding>
         <service name="JCCardTemplateService">
         <port name="JCTemplateServicePort" binding="tns:JCTemplateServiceBinding">
    <soap:address location="http://localhost:8080/jcaa/templateService"/>
    </port>
    </service>
    </definitions>When I use a dynamic proxy to access this service like this:
    public static void main(String[] args) throws Exception
              URL urlWsdl =
                   new URL("http://localhost:8080/jcaa/templateService?WSDL");
              String nameSpaceUri = "urn:JCCardTemplateService";
              String serviceName = "JCCardTemplateService";
              String portName = "JCTemplateServicePort";
              ServiceFactory serviceFactory = ServiceFactory.newInstance();
              Service service =
                   serviceFactory.createService(
                        urlWsdl,
                        new QName(nameSpaceUri, serviceName));
               JCTemplateService myProxy =
                   (JCTemplateService) service.getPort(
                        new QName(nameSpaceUri, portName),
              JCTemplateService.class);
         ->    CardMetaData ct=myProxy.getTemplate("123456");
              System.out.println("CardTemplate from WS is "+ct.getDescription());
              System.out.println("key 1 from WS is "+ct.getKeyENC());
              System.out.println("key 2 from WS is "+ct.getKeyMAC());
              System.out.println("key 3 from WS is "+ct.getKeyKEK());
              System.out.println("Name is "+ct.getName());
         }It fails with a 'deserializzation error incomplete object' error at the line indicated above. If I remove the String[] from the value object and replace it with 3 separate string variables it works.
    Any idea's?
    Mike

    Does this mean, if you need the Dynamic Proxy client approach (and cannot use the Static Stub client, since it's J2EE implementation specific as I've learned from you, Kathy), today you cannot expect String arrays to work in J2EE web services?
    I have got a datatype Foo with an ArrayList containing String Arrays. In webMethods GLUE my server and client understand each other, it works pretty well. But I found that the WSDL is way to complex/not correctly understood by other SOAP client implementations like MS SOAP Toolkit or Mozilla Web Service Implementation.
    So my idea was to switch from GLUE to J2EE. Ok, this leads me to a WS Basic Profile I compliant WSDL and all. But now it seems this works only for really simple java types.
    I really need the ArrayList with the String Array elements. But I think in my web service (WSDL) I have to use a wrapper type which is the String representation of my (serialized by hand) Foo type and I have on the client side to create the Foo type from the string. That would not be nice, my hope was that J2EE supports more in this area. :-) Anyway, at the end it's important for me to have a portable (interoperable!) way to create and use a web service.
    So, to ask the question short and to the point:
    Today, if I want my client to work with different J2EE implementations using the Dynamic Proxy client approach and other clients, like MS SOAP Toolkit, can I offer on the J2EE web service server side a datatype with an ArrayList containing String arrays in a portable and interoperable way without the need of custom deserializers on client side?
    Merten

  • Use array to store negative number

    Hi,
       I use "Initialize array" to set all the 500 elements to "0". Then I input numbers to  "Replace Array Subset"  and generate a new array. But all the positive numbers are correct, negative numbers just become "0". Why? How can I store the negative number in this array?
       Thank you in advance!

    Hi,
    what data type (numeric representation) are you using for the array elements? If it is integer, make sure it's not unsigned (U8, U16, ...) as this data type doesn't allow negative numbers.
    Hope this helps

  • Using arrays with formulas

    I'm having trouble getting my arrays to work in the formula that I need to use to calculate a monthly mortgage payment, which is what I need to do. I'm supposed to use arrays to store three different term year amounts and three different interest rates, and then display the monthly payment and other info for each amount. Can someone help with this? I keep getting errors that say "cannot use operator / or * with double[]". Here is my code:
    class PaymentArray {
         public static void main(String[] arguments) {
              double amount = 100000;
              int[] term = {7, 15, 30};
              double[] rate = {.0535, .055, .0575};
              double payment = (amount*(rate/12))/(1-(Math.pow(1/(1+(rate/12)),(term*12))));
              for (int i = 0; i < term.length; i++) {
                   for (int j = 0; j < rate.length; j++) {
                        System.out.println("If the initial loan amount is " + amount);
                        System.out.println("and the length of the term is " + term + " years");
                        System.out.println("and the monthly interest rate is " + rate);
                        System.out.println("The monthly payment will be " + payment);
    }Any help would be greatly appreciated. Thanks!!! :-)

    That all worked really well, thanks so much!!!
    The only problem I have now is, instead of calculating the payments at 7 years/5.35%, 15 years/5.5%, and 30 years/5.75%, it's calculating them for 7 years at 5.35%, 5.5%, and 5.75%, 15 years at 5.35%, 5.5%, and 5.75%, and so on. I don't need it to do all of that, I need the years to correspond to the correct interest rate. How can I change that? Thank you so much. Here is my new code:
    class PaymentArray {
         public static void main(String[] arguments) {
              double amount = 100000;
              int[] term = {7, 15, 30};
              double[] rate = {.0535, .055, .0575};
              for (int i = 0; i < term.length; i++) {
                   for (int j = 0; j < rate.length; j++) {
                        System.out.println("If the initial loan amount is " + amount);
                        System.out.println("and the length of the term is " + term[i] + " years");
                        System.out.println("and the monthly interest rate is " + rate[j]);
                        double payment = (amount*(rate[j]/12))/(1-(Math.pow(1/(1+(rate[j]/12)),(term*12))));
                        System.out.println("The monthly payment will be " + payment);

  • Help, store an array of cd objects

    im doing a java project on creating a music cd database, i need to store an array of cd objects, each entry in the array will be a single object for a cd.
    The objects are: Artist, Album, No of tracks
    I need some help with this, thanks
    here's the code ive done so far:
    import javax.swing.JOptionPane;
    class Cd1
         public static void main (String[] args)
              int menu_choice;
              CdRecord one = new CdRecord();
              one.artist_name = JOptionPane.showInputDialog("Enter artist name.");
              one.album_name = JOptionPane.showInputDialog("Enter album name.");
              one.no_of_tracks =Integer.parseInt(JOptionPane.showInputDialog("Enter the number of tracks on the album"));
         one.printCdRecord();          
    class CdRecord
         public String artist_name;
         public String album_name;
         public int no_of_tracks;
    public CdRecord (String artist, String album, int tracks, int year)
         artist_name = artist;
         album_name = album;
         no_of_tracks = tracks;
    public CdRecord()
    artist_name = "A";
    album_name = "B";
    no_of_tracks = 0;
    public void printCdRecord ()
    String o = "Artist Name: " + artist_name + "\nAlbum Name: " album_name"\nNo. Of Tracks: " + no_of_tracks;;
    System.out.println(o);
    }

    where should i put this in my code?this part would normally be a class field, accessible from many parts of the class
    java.util.List<CdRecord> records;to it may look something like this
    class Cd1
      private java.util.List<CdRecord> records;//and use constructor to create
      //or
      private java.util.List<CdRecord> records = new java.util.ArrayList<CdRecord>();
      ...as is, the above will cause you a problem because you have most of your code in main() which is static.
    before you go much further, rethink your program design:
    - your class name is Cd1, which would indicate a single CD, but you're doing a CD database so call it CdInventory, CdCollection, etc
    - the only code you want in main() is to start the program, so that would be new CdInventory(), nothing more (unless creating a GUI)
    - how are you going to get new records - a GUI with buttons add/edit/delete, or the console.
    - are you going to save new/edited records to a file (the database), and read existing data back into the program at startup
    - basically how you go about the above determines what you have in the constructor of the program (and do not use main() for this)

  • How to call a method using a array of that object?

    hey, another array question
    for example i have 2 classes one name class and a driver
    inside the name class i have method that gets the name
    public Name getName1( ) {return name1;}
    my question is if i created an array of Name objects in my driver with the following line
    Name [ ] n1 = new Name [ ] ;
    and i wanna call methods inside the name class using my array of Name that i created how do i do it?
    thanks in advance

    thanks for the reply Maxx
    another question regarding arrays
    for example if im doing an array of objects Name[ ] n1 = new Name [ ]
    and i have a method that removes the name if its the same as the user input
    if (n1[ i ].getName.equals(myName))
    / / if they equal it removes it,
    else,
    / / the n[ 1 ] stays the same
    ive search the forum for previous questions on this but their examples doesnt seems to work, can anyone help? also if end up using this remove method that checks the elements in n1 if it matches it will remove it what should i do to avoid nullpointerexceptions if i wanna shift it all down?
    thanks in advance

  • Re: Beginner needs help using a array of class objects, and quick

    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ? In html, I assume. How did you generate the html code of your three classes ? By help of your IDE ? NetBeans ? References ?
    I already posted my question with six source code classes ... in text mode --> Awful : See "Polymorphism did you say ?"
    Is there a way to discard and replace a post (with html source code) in the Sun forum ?
    Thanks for your help.
    Chavada

    chavada wrote:
    Dear Cynthiaw,
    I just read your Beginner needs help using a array of class objects, and quick of Dec 7, 2006 9:25 PM . I really like your nice example.You think she's still around almost a year later?
    I also want to put a question on the forum and display the source code of my classe in a pretty way as you did : with colors, indentation, ... But how ?Just use [code] and [/code] around it, or use the CODE button
    [code]
    public class Foo() {
      * This is the bar method
      public void bar() {
        // do stuff
    }[/code]

  • Array of class objects

    I was wondering how would you declare an array of class objects. Here is my situation:
    I'm working on a project dealing with bank accounts. Each customer has a specific ID and a balance. I have to handle transactions for each customer at different times, so I was thinking that I need an array of class objects; however, I dont know how to initialize them.
    Here's what I did:
    BankAccount [ ] myAccount = new BankAccount[10];
    // 10 = 10 customers
    How do I initialize the objects?
    Thankz

    I was wondering how would you declare an array of
    class objects. Here is my situation:
    I'm working on a project dealing with bank accounts.
    Each customer has a specific ID and a balance. I have
    to handle transactions for each customer at different
    times, so I was thinking that I need an array of
    class objects; however, I dont know how to initialize
    them.
    Here's what I did:
    BankAccount [ ] myAccount = new BankAccount[10];
    // 10 = 10 customers
    How do I initialize the objects?
    Thankz
    HAI
    Use the hashtable
    and store the classObject of each customer with the corresponding Id in it
    and whenever u want to recover a class match the Id and get the corresponding class
    that is the best way to solve ur problem
    Regards
    kamal

  • Array of an Object

    I hope this is the right place to post this but here goes. I am trying to create an array of an object which I have created to store basic details of various people, I have declared the array like this people[] Person = new people[5]; //people is the name of the object but whenever i try to assign values to one of objects, for example Person[number].setName(textName.getText()); //number is predetermined array value to use it throws a null pointer exception. If I define a single instance such as people Person = new people(); it works fine but I specifically need and array. Any help would be greatly appreciated.

    I have to say thanks again, it is working now, all that's left is to change is the naming conventions <img class="emoticon" src="images/emoticons/happy.gif" border="0" alt="" />.

  • Newbie - help needed with array and dictionary objects

    Hi all
    Please see the code below. I've posted this code in another thread however the original issue was resolved and this is now a new issue I'm having although centered around the same code.
    The issue is that I'm populating an array with dictionary objects. each dictionary object has a key and it's value is another array of custom objects.
    I've found that the code runs without error and I end up with my array as I'm expecting however all of the dictionary objects are the same.
    I assume it's something to do with pointers and/or re-using the same objects but i'm new to obj-c and pointers so i am a bit lost.
    Any help again is very much appreciated.
    // Open the database connection and retrieve minimal information for all objects.
    - (void)initializeDatabase {
    NSMutableArray *authorArray = [[NSMutableArray alloc] init];
    self.authors = authorArray;
    [authorArray release];
    // The database is stored in the application bundle.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"books.sql"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
    // Get the primary key for all books.
    const char *sql = "SELECT id, author FROM author";
    sqlite3_stmt *statement;
    // Preparing a statement compiles the SQL query into a byte-code program in the SQLite library.
    // The third parameter is either the length of the SQL string or -1 to read up to the first null terminator.
    if (sqlite3preparev2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
    // We "step" through the results - once for each row.
    // We start with Letter A...we're building an A - Z grouping
    NSString *letter = @"A";
    NSMutableArray *tempauthors = [[NSMutableArray alloc] init];
    while (sqlite3_step(statement) == SQLITE_ROW) {
    author *author = [[author alloc] init];
    author.primaryKey = sqlite3columnint(statement, 0);
    author.title = [NSString stringWithUTF8String:(char *)sqlite3columntext(statement, 0)];
    // FOLLOWING WAS LEFT OVER FROM ORIGINAL COMMENTS IN SQLBooks example....
    // We avoid the alloc-init-autorelease pattern here because we are in a tight loop and
    // autorelease is slightly more expensive than release. This design choice has nothing to do with
    // actual memory management - at the end of this block of code, all the book objects allocated
    // here will be in memory regardless of whether we use autorelease or release, because they are
    // retained by the books array.
    // if the author starts with the Letter we currently have, add it to the temp array
    if ([[author.title substringToIndex:1] compare:letter] == NSOrderedSame){
    [tempauthors addObject:author];
    } // if this is different letter, then we need to deal with that too...
    else {
    // create a dictionary to store the current tempauthors array in...
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    // add the dictionary to our appDelegate-level array
    [authors addObject:tempDictionary];
    // now prepare for the next loop...
    // set the new letter...
    letter = [author.title substringToIndex:1];
    // remove all of the previous authors so we don't duplicate...
    [tempauthors removeAllObjects];
    // add the current author as this was the one that didn't match the Letter and so
    // never went into the previous array...
    [tempauthors addObject:author];
    // release ready for the next loop...
    [author release];
    // clear up the remaining authors that weren't picked up and saved in the "else" statement above...
    if (tempauthors.count > 0){
    NSDictionary *tempDictionary = [NSDictionary dictionaryWithObject:tempauthors forKey:@"authors"];
    [authors addObject:tempDictionary];
    else {
    printf("Failed preparing statement %s
    ", sqlite3_errmsg(database));
    // "Finalize" the statement - releases the resources associated with the statement.
    sqlite3_finalize(statement);
    } else {
    // Even though the open failed, call close to properly clean up resources.
    sqlite3_close(database);
    NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    // Additional error handling, as appropriate...
    Message was edited by: dotnetter

    Ok, so I know what the issue is now...I just don't know enough to be able to resolve it!
    it's the tempAuthors objects.
    It's an NSMutableArray which is create on the line before the start of the WHILE loop.
    Having looked through the debugger, I can see that each dictionary object is created (with different codes which I assume are memory addresses) so all is well there. However, on each iteration of the loop in the middle there is an IF...ELSE... statement which in the ELSE section is clearing all objects from the tempAuthors array and beginning to repopulate it again.
    Looking at the containing dictionary objects in the debugger I can see that the tempAuthors object that each contains has the same code (again, I'm assuming this is a memory address) - so if I understand correctly, it's the same object...I assumed that when I created the dictionary using the dictionWithObject call that I would be passing in a copy of the object, but it's referencing back to the object which I then go on to change.
    Assuming the above is correct, I've tried several "stabs in the dark" at fixing it.
    I've tried relasing the tempAuthors object within the ELSE and initialising it again via an alloc...init - but this didn't work and again looking through the debugger it looks as though it was confused as to which object it was supposed to be using on the following iteration of the WHILE loop (it tried to access the released object).
    Having read a little more about memory management can someone tell me if I'm correct in saying that the above is because the tempAuthors object is declare outside the scope of the WHILE loop yet I then try to re-instantiate it within the loop (does that make sense???).
    Sorry for the long post...the more I can understand the process the less I can hopefully stop relying on others for help so much.
    I am continuing to read up on memory management etc but just not there yet.
    Regards
    Wayne

  • Use array or vector ?

    I need to store data into a 3D array i.e. abc[128][128][128]. Every item of the array is an object.
    My problem is, if i use 3D array to store the data directly, it is too memory costing and always return OutOfMemoryError!!! Also terribly slow !
    Is it better to use vector of vector instead of 3D array? I mean put the 128 objects into a single array and then put 128 single arrays into a vector, lastly put 128 vectors into a new vector.
    Or otherwise, who has any other good suggestions to store these 128*128*128 objects?

    However, that's small compared to the number ofdistinct objects in that space -- 128^3. So the number
    of objects taken up by the arrays or vectors, is less
    than 1% of the number of objects in the 3D space
    defined by the arrays or vectors.
    Sorry, I don't get what you mean ;)
    Yes, it is 1% of the number of objects in the 3D
    space, but you haven't calculate the 4 bytes int value
    used by the int value itself.We're not talking about ints though, are we? The question was about a 3D space of objects.
    So, if let say array Object definition uses 2 bytes,
    then the RAM needed will be:
    Object definition + int values
    ((128^2 + 128 + 1) * 2) + ((128^3) * 4)
    if you create int[128^3], you will only create:
    128^3 * 4Given that problem statement, the array object definitions take up 33026 bytes, whereas the int values take up 8388608. So the memory used by the array object definitions is still just 1% of the memory used. By switching to a 1D array of length 128^3, you're saving less than 1% of the memory. The 33026 bytes isn't the problem here.
    (((128^2 + 128 + 1) * 2) + ((128^3) * 4)) is a much bigger number than ((128^2 + 128 + 1) * 2).
    Just (128^3 * 4) is a much bigger number than ((128^2 + 128 + 1) * 2).
    But anyway that's not the problem statement anyway. There are 128^3 potential objects created in the heap. That's going to be a lot more than the arrays or vectors used to reference them.
    This is why I think the best solution is to look at the data and see if a better approach can be taken than just using 128^3 buckets.
    Another slow but possible solution is using HashMap.
    To check coordinate 33, 75, 109, you can use:
    map.get(new Integer(33*75*109)] and hope Java garbage
    collector runs pretty fast.I wouldn't advise that, because that would cause conflicts between objects at 33,75,109 and 75,33,109, etc. There would be 3! = 6 possible conflicts. If you want to turn the 3D index into a flat 1D index, then multiply each coordinate by a constant to put each into its own range, e.g., (33,75,109)'s 1D index would be (33 * (128^2)) + (75 * 128) + 109.
    Hopefully that's less than the maximum int value. It may not be.
    This solution works fine only if in vast 128*128*128,
    only few hundreds coordinate x,y,z which actually have
    a value. This way you can store the value only if
    needed.Yes, exactly, if the domain data is sparse, a different approach like this would work better than defining 128^3 data buckets.
    If the data is sparse enough, it might be easier to define a 3DCoordinate object to use as the index into the hashtable, than programmatically creating a 1D index.

  • Tic Tac Toe help using array

    Ok i am trying to get a tic tac toe game, which uses array. I need to get 3 buttons and store them then i can check those numbers to see if its a win. Here is my code
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int map[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i< c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String args[] )
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    I couldn't try this out due to a few syntax errors, so fixed some. Now the buttons seem to work.
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int c[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
    private int flag;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3=0;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i < c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String[] args)
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

  • How to pass Array of Java objects to Callable statement

    Hi ,
    I need to know how can I pass an array of objects to PL/SQL stored procedure using callable statement.
    So I am having and array list of some object say xyz which has two attributes string and double type.
    Now I need to pass this to a PL/SQL Procedure as IN parameter.
    Now I have gone through some documentation for the same and found that we can use ArrayDescriptor tp create array (java.sql.ARRAY).
    And we will use a record type from SQL to map this to our array of java objects.
    So my question is how this mapping of java object's two attribute will be done to the TYPE in SQL? can we also pass this array as a package Table?
    Please help
    Thanks

    I seem to remember that that is in one of Oracle's online sample programs.
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/index.html

  • Using a polymorphic view object with binding

    Hi,
    I'm hoping there's something simple I'm missing when trying to setup up the bindings for a ADF/struts page using a polymorphic view object.
    I'm using Entity and VO polymorphism to create a Question which has different types - boolean, multi-choice, likert, etc. I have the various question types created as sub type entity and view objects and added to the app module - when added to the app module the question types are subtypes of QuestionView so they don't actually appear in the Data Controls palette. This setup is like that used in Steve Muench's examples (blog at http://radio.weblogs.com/0118231/stories/2003/02/06/constructingTheDesiredEntityInAPolymorphicViewObject.html and the related undocumented one)
    My question is, how do I get to the data and have jdev create the necessary bindings for the extra attributes the subtype questions have? Since they don't appear as available data controls I can't create a binding iterator or anything for them - short of adding them as spearate view objects (which destroys the whole point of using polymorphism in this case) is there a way to do this?
    Really, the only reason I want to use the polymorphism is so I can have different types of entity validation depending on the type. Should I just simplify this to be one entity object with one VO and put all the validation into "if else's" based on a discriminator?
    Assistance appreciated...
    - Nathaniel

    How else are you planning to associate a JUTableBinding to the 'common' iterator containing all four types of rows and then selectively display them? Perhaps you'd need a custom model over the JUTabelModel that'd filter the rows out.
    I'm not sure if all that trouble is worth it given that your datasets (as far as mentioned in this post) are not large. If these tables/data has to be refreshed/executed a number of times, then you may see the overhead of four queries otherwise it should be fine as database is always faster in filtering rows than doing that in memory.

Maybe you are looking for

  • Problem with memory usage and CPU usage

    Hello, i have a problem with the memory usage and cpu usage in my project! My application must run for more than 24 hrs. The problem is that the longer it runs the bigger is the memory and cpu usage! It starts with ~15% CPU usage and ~70 MBytes memor

  • Dependent Class files of EJBs...

    I have few dependent class files related to all EJBs (for example common exceptione). Right now all these dependent classes are duplicated in all the EJB jars. Is there any way get rid out of this duplication (other than putting in to system class pa

  • Help Link in Portal masthead

    Hi All, 1. Help link in masthead by default points to help.sap.com i have changes it to a help document (Word document) which is residing in KM repository but after clicking on it asks for open, save , cancel oprions instead i wouls like to open the

  • Specified Order Grouping does not show if Distinct Count is Zero

    Post Author: Hieu CA Forum: General Hello, I'm using Crystal Reports XI R2 with SQL data source. I have a cross-tab report with grouping in specified order. It's a report of applicants applying to a college. The grouping is of various majors (degrees

  • Relation for oe_order_headers_all table and tangible id

    Hi all, I have requirement for getting the oe_order_headers_all table header_id based on the iby_trxn_summaries_all table tangible_id. I have the tangible_id based on that need to get the header_id .. please help how the both tables are related, is t