Problem in array

I am developing a simple java mobile game where there has 2 objects collide with each other and trigger an event. Let say object A has an array call aX[] where object B is bX[].
I want to make that whenever ANY member of array aX[] == ANY member of bX[], there will be an even happen. I fail because I am using for loop which like this:
for( i = 0; i < 50; i++ )
if( aX[i] == bX[i] ) {}
It only allow to detect certain aX collide with certain bX such as aX[1] == bX[1] which is not what I want. Can anyone help me on this?

... or make aX and bX both Sets.There's no Set in Java ME. OP wrote:
I am developing a simple java mobile gamedb

Similar Messages

  • Problem in array output, pls help!

    i made an array:
    public class Estudyante
         String studentNo;
         String studentName;
         String address;
         String phone;
         String email;
         public void displayDetails()
              System.out.println(studentNo);
              System.out.println(studentName);
              System.out.println(address);
              System.out.println(phone);
              System.out.println(email);
    public class StudentFinder
         //define the variables of the class
         Estudyante estObjects[];
         //initialize the variables
         public StudentFinder()
              //creating an array of 3 estudyantes
              estObjects = new Estudyante[3];
              //creating objects of all the three elements in an array
              for(int ctr = 0; ctr !=estObjects.length;ctr++)
                   estObjects[ctr] = new Estudyante();
              //assigning test values
              //estudyante 1 details
              estObjects[0].studentNo = "0001";
              estObjects[0].studentName = "Rez";
              estObjects[0].address = "Pasig";
              estObjects[0].phone = "111-1111";
              estObjects[0].email = "[email protected]";
              //estudyante 2 details
              estObjects[1].studentNo = "0002";
              estObjects[1].studentName = "Reza";
              estObjects[1].address = "Manila";
              estObjects[1].phone = "222-2222";
              estObjects[1].email = "[email protected]";
              //estudyante 3 details
              estObjects[2].studentNo = "0003";
              estObjects[2].studentName = "Reza Ric";
              estObjects[2].address = "Malate";
              estObjects[2].phone = "333-3333";
              estObjects[2].email = "[email protected]";
         //declare the method of the class
         public void displayFinder()
              //add the code for displaying estudyante details
              for (int ctr = 0;ctr != estObjects.length;ctr++)
                   estObjects[ctr].displayDetails();
                   //the displayDetails() method is present in the Estudyante class
         //code the main() method
         public static void main(String args[])
              StudentFinder finderObject;
              finderObject = new StudentFinder();
              finderObject.displayFinder();
    problem:
    when i run this in command prompt, it displays all the 3 sets of details
    question:
    how will i display the set of details i want and not all of them?
    eg: i only want the details of studentNo = "0001"
    so in command prompt i execute
    java StudentFinder 0001
    how will i be able to get the details for studentNo = "0001" only and how will i display "No such student" if the studentNo asked for is not in any of the details.

    Hi KikiMon,
    In your displayFinder() method you'll have to take an argument, specifying which Student to display. Like this:
    public void displayFinder(String target)
    for (int ctr = 0;ctr != estObjects.length;ctr++)
    if(estObjects[ctr].studentNo.equals(target)) {
    estObjects[ctr].displayDetails();
    An in your main you'll have to forward a commandline argument like this:
    public static void main(String args[])
    StudentFinder finderObject;
    finderObject = new StudentFinder();
    finderObject.displayFinder(args[0]);
    Later,
    Klaus

  • Problem in Array of JCheckBox

    I am facing a problem with the array of JCheckBox. Without array it works but when I use array it gives NullPointerException. No compile time error. I am using Null Layout. But I need to use the array. How can I solve this?
    Here is the code.
    JCheckBox jCheckBox_Questions[] = new JCheckBox[3];
    JCheckBox box = new JCheckBox();
    Dimension d[] = new Dimension[3] ;
    String strQuestions[] = {"No Child ?","Jaundice ?","Migraine ?"};
    int j=20,k=150;
    // This works
    box.setText(strQuestions[0]);
    add(box);
    d[1]= box.getPreferredSize();
    box.setBounds(j,k,d[1].width,d[1].height);
    k=k+20;
    //When I add the follwing fragment it gives NullPointerException
    jCheckBox_Questions[0]. setText(strQuestions[1]);// in this line
    add(jCheckBox_Questions[0]);
    d[2]= jCheckBox_Questions[0].getPreferredSize();
    jCheckBox_Questions[0].setBounds(j,k,d[2].width,d[2].height);

    Hi,
    classic error: in fact the code
       JCheckBox jCheckBox_Questions[] = new JCheckBox[3]; doesn't instantiate the checkboxes, it's only allocating 3 memory pointers (inited to null), ready to receive the futures instances of checkboxes. So you should have typed:
       JCheckBox jCheckBox_Questions[] = new JCheckBox[3];
       // Here we create the 3 objects
       for (int i=0;i<3;i++) jCheckBox_Questions[ i ] = new JCheckBox();
       //...Hope this will help,
    Regards.

  • A basic question/problem with array element as undefined

    Hello everybody,
    thank you for looking at my problem. I'm very new to scripting and javaScript and I've encountered a strange problem. I'm always trying to solve all my problem myself, with documentation (it help to learn) or in the last instance with help of google. But in this case I am stuck. I'm sure its something very simple and elementary.
    Here I have a code which simply loads a text file (txt), loads the content of the file in to a "var content". This text file contents a font family name, each name on a separate line, like:
    Albertus
    Antenna
    Antique
    Arial
    Arimo
    Avant
    Barber1
    Barber2
    Barber3
    Barber4
    Birch
    Blackoak ...etc
    Now, I loop trough the content variable, extract each letter and add it to the "fontList[i]" array. If the character is a line break the fontList[i] array adds another element (i = i + 1); That's how I separate every single name into its own array element;
    The problem which I am having is, when I loop trough the fontList array and $.writeln(fontList[i]) the result in the console is:
    undefinedAlbertus
    undefinedAntenna
    undefinedAntique
    undefinedArial ...etc.
    I seriously don't get it, where the undefined is coming from? As far as I have tested each digit being added into the array element, I can't see anything out of ordinary.
    Here is my code:
    #target illustrator
    var doc = app.documents.add();
    //open file
    var myFile = new File ("c:/ScriptFiles/installedFonts-Families.txt");
    var openFile = myFile.open("r");
    //check if open
    if(openFile == true){
        $.writeln("The file has loaded")}
    else {$.writeln("The file did not load, check the name or the path");}
    //load the file content into a variable
    var content = myFile.read();
    myFile.close();
    var ch;
    var x = 0;
    var fontList = [];
    for (var i = 0; i < content.length; i++) {
        ch = content.charAt (i);
            if((ch) !== (String.fromCharCode(10))) {
                fontList[x] += ch;
            else {
                x ++;
    for ( i = 0; i < fontList.length; i++) {
       $.writeln(fontList[i]);
    doc.close (SaveOptions.DONOTSAVECHANGES);
    Thank you for any help or explanation. If you have any advice on how to improve my practices or any hint, please feel free to say. Thank you

    CarlosCantos wrote an amazing script a while back (2013) that may help you in your endeavor. Below is his code, I had nothing to do with this other then give him praise and I hope it doesn't offend him since it was pasted on the forums here.
    This has helped me do something similar to what your doing.
    Thanks again CarlosCanto
    // script.name = fontList.jsx;
    // script.description = creates a document and makes a list of all fonts seen by Illustrator;
    // script.requirements = none; // runs on CS4 and newer;
    // script.parent = CarlosCanto // 02/17/2013;
    // script.elegant = false;
    #target illustrator
    var edgeSpacing = 10;
    var columnSpacing = 195;
    var docPreset = new DocumentPreset;
    docPreset.width = 800;
    docPreset.height = 600;
    var idoc = documents.addDocument(DocumentColorSpace.CMYK, docPreset);
    var x = edgeSpacing;
    var yyy = (idoc.height - edgeSpacing);
    var fontCount = textFonts.length;
    var col = 1;
    var ABcount = 1;
    for(var i=0; i<fontCount; i++) {
        sFontName = textFonts[i].name;
        var itext = idoc.textFrames.add();
        itext.textRange.characterAttributes.size = 12;
        itext.contents = sFontName;
        //$.writeln(yyy);
        itext.top = yyy;
        itext.left = x;
        itext.textRange.characterAttributes.textFont = textFonts.getByName(textFonts[i].name);
        // check wether the text frame will go off the bottom edge of the document
        if( (yyy-=(itext.height)) <= 20 ) {
            yyy = (idoc.height - edgeSpacing);
            x += columnSpacing;
            col++;
            if (col>4) {
                var ab = idoc.artboards[ABcount-1].artboardRect;
                var abtop = ab[1];
                var ableft = ab[0];
                var abright = ab[2];
                var abbottom = ab[3];
                var ntop = abtop;
                var nleft = abright+edgeSpacing;
                var nbottom = abbottom;
                var nright = abright-ableft+nleft;
                var abRect = [nleft, ntop, nright, nbottom];
                var newAb = idoc.artboards.add(abRect);
                x = nleft+edgeSpacing;
                ABcount++;
                col=1;
        //else yyy-=(itext.height);

  • HP Proliant ML350G4 server - problem with array

    Hi, I have HP Proliant ML350 G4 server. The problem is that I can not configure the array for SCSI hard drives. When I run the Array Configuration Utility from the SmartStart CD, I get the message: "ACU did not detect any supported controllers in your system." How do I solve this problem?

    Hi:
    You may also want to post your question on the HP Business Support Forum -- ML Servers section.
    http://h30499.www3.hp.com/t5/ProLiant-Servers-ML-DL-SL/bd-p/itrc-264#.U48mculOW9I

  • Problems binding array in C# to stored procedure.

    I'm having trouble trying to pass an array of ID's to a stored procedure that is expecting an array (listed the procedure definition below). My current interface doesn't return an error, but it also doesn't insert the proper id's.
    STORED PROCEDURE DEFINITION:
    TYPE source_ids IS TABLE OF wweb.DM_ASSOCIATIONS.source_id%TYPE INDEX BY PLS_INTEGER;
    PROCEDURE add_message_associations
    (p_dm_message_id IN wweb.dm_messages.dm_message_id%TYPE
    ,p_association_type IN wweb.dm_associations.association_type%TYPE
    ,p_sources IN source_ids
    ,p_create_user IN wweb.dm_associations.create_user%TYPE)
    .......variable definitions here...
    v_source_id := p_sources.First;
    WHILE v_source_id IS NOT NULL
    LOOP
    -- Check if this association already exists.
    -- If not add them.
    v_assoc_exists := 0;
    FOR r_chk IN
    (SELECT 1 AS assoc_exists_flag
    FROM dm_associations a
    WHERE a.dm_message_id = p_dm_message_id
    AND a.association_type = p_association_type
    AND a.source_id = v_source_id)
    LOOP
    v_assoc_exists := r_chk.assoc_exists_flag;
    END LOOP;
    IF v_assoc_exists = 0 THEN
    -- Add the association
    INSERT INTO wweb.dm_associations
    (dm_association_id
    ,dm_message_id
    ,association_type
    ,source_id
    ,source_column_name
    ,active_flag
    ,create_date
    ,create_user
    ,last_update_date
    ,last_update_user)
    VALUES
    (wweb.dm_associations_s.NEXTVAL
    ,p_dm_message_id
    ,p_association_type
    ,v_source_id
    ,v_source_column_name
    ,1
    ,SYSDATE
    ,p_create_user
    ,SYSDATE
    ,p_create_user);
    END IF;
    .......error handling here...
    C# CODE:
    OracleParameter[] param = new OracleParameter[4];
    param[0] = new OracleParameter("p_dm_message_id", OracleDbType.Long);
    param[1] = new OracleParameter("p_association_type", OracleDbType.Varchar2, 5);
    param[2] = new OracleParameter("p_sources", OracleDbType.Int32);
    param[3] = new OracleParameter("p_create_user", OracleDbType.Varchar2, 25);
    param[0].Value = 1;
    param[1].Value = "ER";
    param[2].Value = new Int32 [] {1, 172, 412, 7953};
    param[3].Value = "SVC-GDESAI";
    param[2].CollectionType = OracleCollectionType.PLSQLAssociativeArray;
    param[2].Size = 4;
    param[2].ArrayBindStatus = new OracleParameterStatus[4]{OracleParameterStatus.Success, OracleParameterStatus.Success, OracleParameterStatus.Success, OracleParameterStatus.Success};
    cn = new OracleConnection(ConnectionString);
    cn.Open();
    OracleCommand cmd = new OracleCommand();
    cmd.Connection = cn;
    cmd.CommandText= "dynamic_messages_api.add_message_associations";
    cmd.CommandType= CommandType.StoredProcedure;
    foreach (OracleParameter p in param)
    if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) && (p.Value == null || p.Value.ToString() == ""))
    p.Value = DBNull.Value;
    cmd.Parameters.Add(p);
    cmd.ExecuteNonQuery();
    This ran fine, and created four rows in the table, but the source id's were (1, 2, 3, 4) instead of (1, 172, 412, 7953) which were the ones I passed in.
    Does anyone know what I'm doing wrong here?
    Thanks,
    Gauranga

    Hi,
    I think you have a problem in you PL/SQL procedure. When you receive an array in the procedure, it is your responsibility to parse it explicitely with a loop or to bulk insert with a "forall" (implicit).
    For instance, here is an example of a procedure of mine. I don't catch exceptions as I want the C# calling code to know about them:
    The type t_* are defined like yours.
    procedure UpdateDistribDates(p_bannerid in t_bannerid,
    p_promonumber in t_promonumber,
    p_datenumber in t_datenumber,
    p_actualdate in t_actualdate ) is
    BEGIN
    -- First delete the existing dates in bulk
    FORALL I IN P_BANNERID.FIRST..P_BANNERID.LAST
    DELETE FROM PROMODISTRIBDATE
    WHERE BANNERID = P_BANNERID(I)
    AND PROMONUMBER = P_PROMONUMBER(I);
    -- Then, insert the values passed in arrays.
    FORALL I IN P_BANNERID.FIRST..P_BANNERID.LAST
    INSERT INTO PROMODISTRIBDATE
    (BANNERID,
    PROMONUMBER,
    DATENUMBER,
    ACTUALDATE)
    VALUES (P_BANNERID(I),
    P_PROMONUMBER(I),
    P_DATENUMBER(I),
    P_ACTUALDATE(I));
    END;
    As you can see, the FORALL keyword will process the arrays passed as any other PL/SQL array in one chunk.
    When you do the insert like:
    INSERT INTO wweb.dm_associations
    (dm_association_id
    ,dm_message_id
    ,association_type
    ,source_id
    ,source_column_name
    ,active_flag
    ,create_date
    ,create_user
    ,last_update_date
    ,last_update_user)
    VALUES
    (wweb.dm_associations_s.NEXTVAL
    ,p_dm_message_id
    ,p_association_type
    ,v_source_id
    ,v_source_column_name
    ,1
    ,SYSDATE
    ,p_create_user
    ,SYSDATE
    ,p_create_user);
    In source_id, you insert the index of the table, not the value of the field.
    I would suggest you completely rewrite this procedure by using the explicit loop like this:
    1/ Explicit loop
    FOR i IN 1 .. p_sources.COUNT LOOP
    -- Check the existence
    EXIST_FLAG := 0;
    BEGIN
    SELECT 1
    INTO EXIST_FLAG
    FROM ...
    WHERE ...
    AND a.source_id = p_source(i) <-- You are parsing here
    AND ...
    EXCEPTION
    WHEN OTHERS THEN -- Nothing was found
    EXIST_FLAG := 0;
    END;
    IF (EXIST_FLAG = 1)
    INSERT INTO wweb.dm_associations
    (dm_association_id
    ,dm_message_id
    ,association_type
    ,source_id
    ,source_column_name
    ,active_flag
    ,create_date
    ,create_user
    ,last_update_date
    ,last_update_user)
    VALUES
    (wweb.dm_associations_s.NEXTVAL
    ,p_dm_message_id
    ,p_association_type
    ,p_source(i) <-- You parse here
    END IF;
    END LOOP;
    2/ Implicit loop and bulk insert
    You would need to completely review the logic and build an array that maps exactly the row of the table you are trying to insert into. Parse the array and check for the existence of your entry, delete the row in memory when not found, then, after the loop do a bulk insert with a "forall".
    Hope it helps,
    Patrice

  • URGENT: Problem sending array of complex type data to webservice.

    Hi,
    I am writing an application in WebDynpo which needs to call External web service. This service has many complex data types. The function which I am trying to access needs some Complex data type array. When i checked the SOAP request i found that the namespace for the array type is getting blank values. Because of which SOAP response is giving exception.
    The SOAP request is as below. For the <maker> which is an array ,the xmlns:tns='' is generated.
    <mapImageOptions xsi:type='tns:MapImageOptions' xmlns:tns='http://www.themindelectric.com/package/com.esri.is.services.glue.v2.mapimage/'>
    <dataSource xsi:type='xs:string'>GDT.Streets.US</dataSource>
    <mapImageSize xsi:type='tns:MapImageSize'><width xsi:type='xs:int'>380</width><height xsi:type='xs:int'>500</height></mapImageSize>
    <mapImageFormat xsi:type='xs:string'>gif</mapImageFormat>
    <backgroundColor xsi:type='xs:string'>255,255,255</backgroundColor>
    <outputCoordSys xsi:type='tns:CoordinateSystem' xmlns:tns='http://www.themindelectric.com/package/com.esri.is.services.common.v2.geom/'>
    <projection xsi:type='xs:string'>4269</projection>
    <datumTransformation xsi:type='xs:string'>dx</datumTransformation>
    </outputCoordSys>
    <drawScaleBar xsi:type='xs:boolean'>false</drawScaleBar>
    <scaleBarPixelLocation xsi:nil='true' xsi:type='tns:PixelCoord'></scaleBarPixelLocation>
    <returnLegend xsi:type='xs:boolean'>false</returnLegend>
    <markers ns2:arrayType='tns:MarkerDescription[1]' xmlns:tns='' xmlns:ns2='http://schemas.xmlsoap.org/soap/encoding/'>
    <item xsi:type='tns:MarkerDescription'><name xsi:type='xs:string'></name>
    <iconDataSource xsi:type='xs:string'></iconDataSource><color xsi:type='xs:string'></color>
    <label xsi:type='xs:string'></label>
    <labelDescription xsi:nil='true' xsi:type='tns:LabelDescription'>
    </labelDescription><location xsi:type='tns:Point' xmlns:tns='http://www.themindelectric.com/package/com.esri.is.services.common.v2.geom/'>
    <x xsi:type='xs:double'>33.67</x><y xsi:type='xs:double'>39.44</y>
    <coordinateSystem xsi:type='tns:CoordinateSystem'>
    <projection xsi:type='xs:string'>4269</projection>
    <datumTransformation xsi:type='xs:string'>dx</datumTransformation>
    </coordinateSystem></location></item>
    </markers><lines xsi:nil='true'>
    </lines><polygons xsi:nil='true'></polygons><circles xsi:nil='true'></circles><displayLayers xsi:nil='true'></displayLayers>
    </mapImageOptions>
    Another problem:
    If the webservice is having overloaded methods , it is generating error for the second overloaded method.The stub file itself contains statment as follow:
    Response = new();
    can anyone guide me on this?
    Thanks,
    Mital.

    I am having this issue as well.
    From:
    http://help.sap.com/saphelp_nw04/helpdata/en/43/ce993b45cb0a85e10000000a1553f6/frameset.htm
    I see that:
    The WSDL document in rpc-style format must also not use any soapenc:Array types; these are often used in SOAP code in documents with this format. soapenc:Array uses the tag <xsd:any>, which the Integration Builder editors or proxy generation either ignore or do not support.
    You can replace soapenc:Array types with an equivalent <sequence>; see the WS-I  example under http://www.ws-i.org/Profiles/BasicProfile-1.0-2004-04-16.html#refinement16556272.
    They give an example of what to use instead.
    Of course I have been given a WSDL that has a message I need to map to that uses the enc:Array.
    Has anyone else had this issue?  I need to map to a SOAP message to send to an external party.  I don't know what they are willing to change to support what I can do.  I changed the WSDL to use a sequence as below just to pull it in for now.
    Thanks,
    Eric

  • NullPointer Problems in Array

    I'm trying to create two different hash tables, and put the hased data into each one using linear probing. I'm using an array, but I'm having a little problem (mainly with the circular array part, I think). I've posted what I've got below. Every time I try to test it, I get a NullPointerException. I know the code is a little (a lot) sloppy, but I just sat down and wrote it right now, so take it easy :P
    import java.util.Scanner;
    import java.io.*;
    public class HashingTable {
         private static HashObject[] array1;
         private static HashObject[] array2;
         private static int collision1, collision2;
         public HashingTable() {
              HashObject[] array1 = new HashObject[145];
              HashObject[] array2 = new HashObject[415];
              collision1 = collision2 = 0;
         public static void fillHashTable(String fileName) throws IOException {
            Scanner scan = new Scanner(new File(fileName));
            while(scan.hasNext()) {
                HashObject hashObject1, hashObject2;
               String word = scan.next().toUpperCase();
                        int total = 0;
                        for(int i=0; i < word.length(); i++) {
                             char c = word.charAt(i);
                             if(Character.isLetterOrDigit(c))
                                  total += (int)c;
                             if(c == '-')
                                  total += (int)c;
                             if(c == '/')
                                  total += (int)c;
                        int hashedInt_1 = total%135;
                        hashObject1 = new HashObject(word, hashedInt_1);
                        int hashedInt_2 = total%401;
                        hashObject2 = new HashObject(word, hashedInt_2);
                        for(int j=0; j < array1.length; j++) {
                             if(j == hashedInt_1)
                                  if(array1[j] == null)
                                       array1[j] = hashObject1;
                                  else
                                       while(array1[j] != null) {
                                       j++;
                                       collision1++;
                                            if(j+1 > array1.length)
                                            j = 0;
                        for(int k=0; k < array2.length; k++) {
                             if(k == hashedInt_2)
                                  if(array2[k] == null)
                                       array2[k] = hashObject2;
                                  else
                                       while(array2[k] != null) {
                                       k++;
                                       collision2++;
                                            if(k+1 > array2.length)
                                                 k = 0;
      private static class HashObject {
                protected String hashedWord;
              protected int hashedValue;
              public HashObject(){}
              public HashObject(String s, int n) {
                   hashedWord = s;
                   hashedValue = n;
    }Also, it made me mark my instance variables as static, why is that?

    Wait a minute... I just realized that several things are awkward in your code. For example, why do you loop until you find k to be equal to the other number? Here is a revision:
                                  if(array1[hashedInt_1] == null)
                                       array1[hashedInt_1] = hashObject1;
                                  else
                                       for(int j = 0; the thing doesn't equal null; j++) {
                                       collision1++;
                                            if(j+1 == array1.length)
                                                j = -1;
                                                             //check if the array1[j] is null. If it is, then change it and break the loop
                                                             }I think the error in the circle is that you have 2 loops for no reason, and the inner loop is not doing anything - it's value doesn't reset.
    Edited by: Student_Coder on Dec 4, 2007 8:13 PM

  • Output problem in array, code included.

    Been hacking away at a starting java class for a few months now, and never had to resort to asking you guys for help.
    However, i missed class all week due to work conflicts, so i couldn't question my professor on this problem. Oddly, the actual array bits i'm fine with, but the output has me stalled.
    The program is ment to square the numbers 1-10, and then it wants me to output the square and the original number on the same line (It also wanted me to use Math.pow to get the squares, but that gave me a whole slew of syntax errors i couldn't figure out, so i did it the easy way).
    I'm not sure how to do this, have tried quite a few things, but i'm fairly certain i'm just missing something obvious, any tips would be helpful.
    import javax.swing.*;
    public class J6E1 {
       public static void main( String args[] )
          int []  Data = new int [11];
          for (int x=1; x<Data.length; x++)
              Data[x]  =  (x*x);
          for  (int x=1; x<Data.length;x++)
                   System.out.println(Data[x] );
          System.exit(0);
    }

    So for a given x, you have stored x*x value in Data[x].
    What about printing both x and Data[x] then?

  • Another question about problem using arrays

    Hey guys, if you helped me answer my other problems thanks a bunch and again thank you to all the people who try to help us learn the unique language of Java. Anyway the other problem goes like this:
    Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
    countEvens({2, 1, 2, 3, 4}) ?? 3
    countEvens({2, 2, 2}) ?? 3
    countEvens({1, 3, 5}) ?? 0
    Ok so basically I would want to count all the evens in an array and basically if I use the module operator I can figure out whether something is even or not if it returns me a 0. So I know there will be an if statement there. I'm wondering if I would have to also use a "for each" statement to check every element. I would also need a variable to keep count of the number of elements that are even. Any suggestions on how the implementation of this method should be like?

    Hey thanks a bunch actually, I just pretty much reasoned it out and ended up with this:
    public int countEvens(int[] nums) {
    int count = 0;
    for (int e:nums)
         if ((e%2)==0)
            count++;
       return count;      
    }Really appreciate the help.

  • Question about problem using arrays...

    Hey guys, thanks a bunch for the help - I always really appreciate how you guys can take the time to help us people still learning about this amazing language. Anyway the problem goes like this:
    Given an int array, return a new array with double the length where its last element is the same as the original array, and all the other elements are 0. The original array will be length 1 or more. Note: by default, a new int array contains all 0's.
    makeLast({4, 5, 6}) ?? {0, 0, 0, 0, 0, 6}
    makeLast({1, 2}) ?? {0, 0, 0, 2}
    makeLast({3}) ?? {0, 3}//this is basically what it's supposed to do
    public int[] makeLast (int[] nums)
    So I'm just wonder on how the implementation would be like. I know that I would first want to double the array length. After that, I would want to replace every element of the original array with 0's but keep the last element the same. Any suggestions guys?

    So I'm just wonder on how the implementation would be like. I know that I would first want to double the array length.Well, you can't double the length per se. You can't dynamically change the size of an array. Rather, you'll need to create a new array with the size as specified by the homework assignment.
    After that, I would want to replace every element of the original array with 0's but keep the last element the same.Since it's a new array, you wouldn't actually replace anything.
    Any suggestions guys?Hint: the default value, in an array of numbers, is zero.

  • Problem with arrays

    Hi guys am having difficulty to access an array from another method in the came class
    import java.io.*;
    class arr
         int i,j,k;
         int r;
         int arr1[][] = new int [30][30];          
         void input() throws IOException
         InputStreamReader ir= new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(ir);
         String s= br.readLine();
         int r = Integer.parseInt(s);
         System.out.println("Value of r is:"+r);
              for(i=0;i<r;i++)
                   for(j=0;j<5;j++)
                   arr1[i][j]=k;
                   k++;
         void display()
         System.out.println("r is"+r); // When executed r = o
              for(i=0;i<r;i++)
                   for(j=0;j<5;j++)
                   System.out.println(arr1[i][j]);
    class testing
         public static void main(String args[]) throws IOException
         arr a = new arr();
         a.input();
         a.display();
    }How come that r =0 when i input another value?
    Please guys how can i overcome this problem??
    thanks

    Ok TIM ill see for the variables i and j
    For the array of size 30x30 ,i have already done what u said but had problems to access it in the display() so ive done it that way ..Guys i' having problems in the do....while loop (main ())
    normally when i input "Y" i should be promped to the menu but the programs ends....
    import java.io.*;
    class volley
         int i,j;
         int r;
         String arr1[][] = new String [30][30];
         String criteria;          
         void input() throws IOException
         InputStreamReader ir= new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(ir);
         System.out.print("Enter number of volleyball teams:");
         String s= br.readLine();
         r = Integer.parseInt(s);
              for(i=0;i<r;i++)
                   System.out.println();
                   System.out.print("Enter Information for Volleball  team "+(i+1));
                   System.out.println();
                   for(j=0;j<5;j++)
                   if (j==0)
                   criteria = "1.Team Name";
                   else if(j==1)
                   criteria = "2.City";
                   else if(j==2)
                   criteria = "3.Number of Wins";
                   else if(j==3)
                   criteria = "4.Number of losses";
                   else
                   criteria = "5.Number of Hits";
                   System.out.print(criteria+" is :" );
                   String k = br.readLine();
                   arr1[i][j]=k;
         void display()
              for(i=0;i<r;i++)
                   System.out.println();
                   System.out.println("Displaying volleball team:"+(i+1));
                   System.out.println();
                   for(j=0;j<5;j++)
                   if (j==0)
                   criteria = "1.Team Name";
                   else if(j==1)
                   criteria = "2.City";
                   else if(j==2)
                   criteria = "3.Number of Wins";
                   else if(j==3)
                   criteria = "4.Number of losses";
                   else
                   criteria = "5.Number of Hits";
                   System.out.println(criteria+ "is:" +arr1[i][j]);
    class tennis
    {     String arrtennis[][]=new String[30][30];
         int r;     
         String criteria;
         void inputtennisinfo() throws IOException
         InputStreamReader ir= new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(ir);
         System.out.print("Enter number of tennis teams:");
         String s= br.readLine();
         r = Integer.parseInt(s);
         for (int i=0;i<r;i++)
              System.out.println();
              System.out.println("Enter information for tennis team: "+(i+1));
              System.out.println();
              for(int j =0;j<5;j++)
              if (j==0)
              criteria = "1.Team Name";
              else if(j==1)
              criteria = "2.City";
              else if(j==2)
              criteria = "3.Number of Wins";
              else if(j==3)
              criteria = "4.Number of losses";
              else if (j==4)
              criteria="5.Number of hits";
              else
              criteria = "5.Number of errors";
              System.out.print(criteria+ " is: ");
              String k=br.readLine();
              arrtennis[i][j]=k;     
         void display()
         for(int i=0;i<r;i++)
              System.out.println();
              System.out.println("Displaying volleball team:"+(i+1));
              System.out.println();
              for(int j=0;j<5;j++)
              if (j==0)
              criteria = "1.Team Name";
              else if(j==1)
              criteria = "2.City";
              else if(j==2)
              criteria = "3.Number of Wins";
              else if(j==3)
              criteria = "4.Number of losses";
              else if (j==4)
              criteria="5.Number of hits";
              else
              criteria = "5.Number of errors";
              System.out.println(criteria +" is"+arrtennis[i][j]);     
    class testing
         public static void main(String args[]) throws IOException
         String yn;
         InputStreamReader irr= new InputStreamReader(System.in);
         BufferedReader brr = new BufferedReader(irr);
         volley a = new volley();
         tennis t = new tennis();
         do                                               //  loop is here
         System.out.println("*********WELCOME TO TEAM PROGRAM***********");
         System.out.println("1.INPUT VOLLEBALL INFORMATION");
         System.out.println("2.INPUT TENNIS INFORMATION");
         System.out.println("3.DISPLAY VOLLEBALL INFORMATION");
         System.out.println("4.DISPLAY TENNIS INFORMATION");
         System.out.print("Your choice is: ");
         String str=brr.readLine();
         int choice=Integer.parseInt(str);
         switch(choice)
              case 1:
                   a.input();
                   break;
              case 2 :
                   t.inputtennisinfo();
                   break;
              case 3:
                   a.display();
                   break;
              case 4:
                   t.display();
                   break;
              default:
                   System.out.println("Wrong Input");
         System.out.print("Do you want to continue(Y/N):");
         yn=brr.readLine();
         if(yn=="N")
         System.out.println("Good Bye");     
         while(yn=="Y");
    }Thanks guys

  • I'm having problems manipulating array data within a for loop, and extracting the required sub-arrays generated.

    Hi,
    I'm using labVIEW V5.1
    I'm trying to generate 10 1D arrays, the first array is initialized to all zeroes, then I have set up a for loop which shifts the first element by 1, then a random number is placed into the first element position. I am using a shift register to feed back in the newly generated array into the start of the loop.
    By the end of the each loop I want to be able to use the array generated in an algorithm outside the loop. However I only want the Nx1 array that has just been generated.
    Unfortunately, I cannot figure out how to resize, reshape or index the output array to do this.
    I would like the loop to
    give me out a 1D array after each iteration.
    Any help would be greatly appreciated.

    I hope I've understood your problem.
    First your vi was lacking of the sub-vi working as shift register, I've replaced it with the rotate function.
    The indexing of your arrays create a 2D array whose rows are your 1D array.To pick only one of them you have to use the index array function and select which one you want.
    To use your temporary data in another part of your application you should use a local variable of array2.
    I did it in a separated while loop That I syncronized with the for loop using occurrence, in this way the while loop runs each time a new value is inserted in array2 (each loop of the for loop structure).
    If you don't need this syncronization just get rid of occurrence functions.
    I place a delay in the for loop to show what happens when running.
    Hope it was helpful.
    Alberto Locatelli
    Attachments:
    array_test_v3.vi ‏35 KB

  • Problem returning array of strings

    Hi,
    I am trying to return an array of strings from C to Java.The function I am using is
    char rec[20][20];
    int num=0;
    /* incrementing num and copying into the array everytime a record is added*/
    JNIEXPORT jobjectArray JNICALL Java_jnimidlet_list_1rec
    (JNIEnv *env, jobject obj)
    jstring str;
    jobjectArray args = 0;
    jsize len = num;
    int i=0;
    args = (*env)->NewObjectArray(env, len,
    (*env)->FindClass(env, "java/lang/String"), 0);
    for( i=0; i < len; i++ )
    str = (*env)->NewStringUTF( env, rec);
    (*env)->SetObjectArrayElement(env, args, i, str);
    return args;
    In the java code:
    String []all=list_rec();
    when this function is called I get the error:
    Unhandled exception
    Type=GPF vmState=0xffffffff
    ExceptionCode=0xc0000005 ExceptionAddress=0x00000000 ContextFlags=0x0001003f
    Handler1=0x10f01530 Handler2=0x10026280
    Module=C:\wsdd5.5\wsdd5.0\ive\bin\j9.exe
    Module_base_address=0x00000000
    Offset_in_DLL=0x00000000
    EDI=0x0012fc14 ESI=0x10f01530 EAX=0x00020020
    EBX=0x00148e34 ECX=0x0017469c EDX=0x00020020
    EBP=0x00149d40 ESP=0x0012fbec EIP=0x00000000
    Thread: main (priority 5) (LOCATION OF ERROR)
    Thread: Gc Thread (priority 5) (daemon)
    Can anyone pls tell me how do I come out of this problem.
    Please help.
    Thanx in advance,
    pri_rav

    Hi Priya,
    I dont see any problem. I tried to work with your code it works fine without any exception. Please make sure all ur rec char buff contents are null terminated and your 'i' counter is initialized properly and stops properly. According to me there shouldn't be any problem with JVM. I hope you are aware of c programming,which doesn't check for array boundaries. You may accidentally go out of array size allocated. So my suggession is to check you rec buff going above any of the dimension. Put a watch on 'i' variable content as well. Try and let me know whether it solves your problem. If it doesn't reply me with more details. I will try helping you.
    Thanks,
    Regards,
    Ravikiran.

  • Problem creating array... help!!!

    Hi everyone, Im currently trying to do a project and I am a little suck. Could anyone please help?
    I have two classes. The first class is Ticket, which is an int array of 6, the other class is called TicketArray, which is an array of objetcs tickets. The ints stored on the tickets are read from an ASCII file on TicketArray class, and send samehow to the ticket object, which is later store on the TicketArray. I've got this far:
    public class Ticket
       private int token;
       public void main(String args[], int theToken)
       int num[];
       num = new int[5];
       token = theToken;
       }and the next class is
    import java.io.*;
    import java.util.*;
    public class TicketArray;
      static BufferedReader fileInput;
        public static void main(String args[]) throws IOException  //exception there in case the file cannot be found.
            String first;
            StringTokenizer tokenizer;
            int num1, index=0; int theToken;
            String [] t = new String[30];
            fileInput = new BufferedReader(new FileReader("Lotto.dat"));
            first = fileInput.readLine();
            tokenizer = new StringTokenizer(first);
            int numberOfTokens = tokenizer.countTokens();
            while (first!= null)
                int t[] = new t[5]
                int a = new Ticket(int t[], num);  //// PROBLEM HERE
                while (tokenizer.hasMoreTokens())
                    for (index = 0; index< s.length; index++)
                    theToken = Integer.parseInt(tokenizer.nextToken());
                    s[index] = theToken;
                    System.out.println(t[i] + " " + numberOfTokens);
                t[index] = new String(first);
                index++;
                first = fileInput.readLine();
            fileInput.close();
            System.out.println("File read and closed");

    and then i saw you do this
    t[index] = new String(first);
    t is an int array, so you are trying to assign a string to an int, which also wont work.
    Edited by: mkoryak on Nov 16, 2007 2:33 PM
    also you say this:
    int num[];
    num = new int[5];
    this initializes an int array of 5 and then throws it away as soon as the constructor main method returns. i dont think you want that. you should the declairation up top where the int token is.
    ok, so you dont have a constructor for the ticket class that matches the one you are trying to use.
    i think you may need to go back to the examples, you have more problems in this code then there is lines of code.
    Edited by: mkoryak on Nov 16, 2007 2:34 PM

  • Problem searching array

    I have an array in a column that I extracted from a data file. I want
    to search the array for particular values and return the index which
    is easily implemented by the search 1d array subvi. However, when I
    input the values to search, it returns a -1 for some values and others
    it finds fine where I know all the values exist. To be more precise,
    my array is about 80 values between -2 and 2 in steps of 0.05. When I
    search for -2, -1.5, -1, etc., I get the correct index. When I search
    for other numbers like -1.8, -1.7, -1.85, etc., I get a return value
    of -1. It is really strange and I am not sure of the problem. Anyone
    have any ideas? Does it have anything to do with the precision or how
    I read the spreadsheet file to extract the column?
    T
    hanks
    Heather

    Thanks for all your help. I ended up converting both the search array
    and the search element to strings with 2 decimal point precision and
    it works fine.
    You guys are the best.
    Heather
    [email protected] (H) wrote in message news:<[email protected]>...
    > I have an array in a column that I extracted from a data file. I want
    > to search the array for particular values and return the index which
    > is easily implemented by the search 1d array subvi. However, when I
    > input the values to search, it returns a -1 for some values and others
    > it finds fine where I know all the values exist. To be more precise,
    > my array is about 80 values between -2 and 2 in steps of 0.05. When I
    > search for -2, -1.5, -1, etc., I get the correct index. When I
    search
    > for other numbers like -1.8, -1.7, -1.85, etc., I get a return value
    > of -1. It is really strange and I am not sure of the problem. Anyone
    > have any ideas? Does it have anything to do with the precision or how
    > I read the spreadsheet file to extract the column?
    >
    > Thanks
    > Heather

Maybe you are looking for

  • Just purchased a 15" Macbook Retina Which model do I have?

    Hello everyone, Today I was lucky enough to purchase an open box 15" Macbook Pro Retina from Best Buys for $1200 (With some store manager employ discounts ) and I wanted to know which model I have. For example from the first day they released the 15"

  • Need help installing Windows with Parallels on Mac Mini

    I downloaded the trial version of Parallels to test it out. Everything is going fine until it asks me to restart my computer. I go through the basic setup at the beginning, it asks me to enter the Windows XP product key and then asks me to insert the

  • Cannot Load iTunes 10.0 Because "iPod service could not be installed".

    When I tried to upgrade to iTunes 10.0 I received an error message and was told to uninstall and reinstall iTunes. When I tried to install 10.0 . I got the following error message "Service 'iPod Service' (iPod Service) could not be installed. Verify

  • Share Configuration Manager Entries between WebDynpro and EJB

    Hi there, I have an annoying problem: I would like to have a WebDynpro as full-blown configuration interface for my EJBs. As steted in the docu, it is not possible to share configurations between applications. With EJB and Web Modules I would just pl

  • I need help with a bad system /etc/profile

    I need your help, I put an exec line in the wrong place, it reads like this: exec /usr/local/bin/spillman I meant to put in into the etc/skel/.profile, I didn't have that app installed yet, and now when I try and login, even as root, I get looped bac