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.

Similar Messages

  • Array of JCheckBox?

    Hello,
    I am trying to create an array of JCheckBox objects. Here is the code. I do not get any error message with the javac command then the Applet doesn't work. Something is wrong but where?
    Thanks in advance
    Christos
    import javax.swing.*;
         import java.lang.*;
         public class Test extends JApplet
    {//opens the class
         private JPanel mypanel;
         private JCheckBox[] cha;
         public void init()
    try {
    javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
    public void run() {
    createGUI();
    } catch (Exception e) {
    System.out.println("createGUI didn't successfully complete");
    }//closes init
         private void createGUI() {
         mypanel=new JPanel();
         cha = new JCheckBox[10];
         for (int i=1; i<=10;i++){
         cha= new JCheckBox(String.valueOf(i),false);
         mypanel.add(cha[1]);
         this.getContentPane().add(mypanel);
         }//ends createGUI()
    } // Ends class

    Try to replace statement...
    cha= new JCheckBox(String.valueOf(i),false);
    with...
    cha.setText(String.valueOf(i));
    cha[i].setSelected(false);
    as shown below...
    for (int i=1; i<=10;i++){
    //cha= new JCheckBox(String.valueOf(i),false);
         [b]cha.setText(String.valueOf(i));
         cha[i].setSelected(false);

  • Problem with JTable with JCheckBox as Header

    Hi,
    We have a JCheckBox as JTable Header. And respective data in that column also check boxes. For data check boxes, just i am sending Boolean object to object[][] data array. I am getting check Boxes as data components.
    For Header, i have create a TableRender object which is returning JCheckBox.
    Here my problem is,
    1) When i select a Header check box, all the check boxes are getting selected.
    2) Now we can reselect an data Check Box. When i reselect any data checkBox, Header CheckBox should be reselected. This is not happening. I was tried lot. Can any body give a solution to solve this problem.
    Please .... Please ...
    Thanks
    Mohan

    just call this method with null param on the JTable
    table.setTableHeader(null);
    cheers
    krishna

  • 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

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

  • Problem with Icon in JCheckBox

    I have a problem with a JCheckBox, when I assign an Icon to it, the checkBox dissapears and the only thing I see is the Icon. Is there a way to have the CheckBox and the Icon?
    Thanks
    Alejandro

    class MyCheckBox extends JPanel {
      JCheckBox jcb = new JCheckBox();
      JLabel jl;
      public MyCheckBox(String s, Icon i) {
        add(jcb);
        jl = new JLabel(s,i, JLabel.LEFT);
        add(jl);
      public boolean isSelected() { return jcb.isSelected(); }
      public void setSelected(boolean b) { jcb.setSelected(b); }
      public String getText() { return jl.getText(); }
      public void setText(String s) { jl.setText(s); }
      public Icon getIcon() { return jl.getIcon(); }
      public void setIcon(Icon i) { jl.setIcon(i); }
    }

  • 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

Maybe you are looking for

  • Modification in report into ALV Format

    Hi Experts How can I modify this report in ALV Format with Top of page and Parameters should be display on runtime. Can anyone modify my program please Thanks in advanced. REPORT FZEL LINE-SIZE  220 LINE-COUNT 75          NO STANDARD PAGE HEADING. TA

  • Media Center PC m7250n hangs on Windows 7 final install phase.

    When I try to install Windows 7 (32bit) on my m7250n, the process comes to the final “Completing Installation” phase and hangs. The hang apparently occurs immediately after the boot-up into Win7 that commences this final phase. The progress bar just

  • Blueman-git OBEX file transfer not working

    blueman-git's OBEX file transfer is not working.  For the bluetooth stack I am using the Bluez5. When I start blueman-services, the following shows up: totakura@iris:~$ blueman-services Loading configuration plugins Using GConf config backend blueman

  • Where to find Power Adapter for iBook - 65W Model A1021?

    Does anyone know where I can find a new power adapter for an older iBook? Details: Apple 65W Portable Power Adapter Model No. A1021 Cord seems to be fine, just need the brick. Thank you!! Teresa

  • Itunes download error tap to retry - iphone 5s

    When downloading a song from itunes on my iphone I got the download error tap to retry. I tried restarting the iphone, signing out of itunes and restarting but still got the same error, but I can download new songs fine. So I connected the iphone to