13 Replies - 5918 Views - Last Post: 31 August 2010 - 06:38 PM Rate Topic: -----

#1 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Adding an Element to an Array

Posted 31 August 2010 - 10:29 AM

Some places online say that you can't add an element to an array in java. My instructor says differently. My code looks like this:


                     if(size <= data.length)
                      for(H = size; H > I; H--)
                       {
                           data[H] = data[H-1];
                       }
                         data[I+1] = newb;
                         size++;




Clearly I am getting an OutofBounds exception at this point... I was just wondering if anyone had any suggestions. For instance, should I return size to the print function? The reason I ask is because this doesn't seem necessary when I delete. The summary table doesn't contain extra blanks when I print after removing elements.

ETA: (Sorry for missing info "size" is my counter for the size of the array, and "I" is my position indicator.)

This post has been edited by jhar131: 31 August 2010 - 10:32 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Adding an Element to an Array

#2 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Adding an Element to an Array

Posted 31 August 2010 - 10:44 AM

Valid array indexes are 0 -(size-1). If 'size' is set equal to the length of the array (which it can be according to your conditional), then H can be the size of the array, which is not a valid index.
Was This Post Helpful? 0
  • +
  • -

#3 ipushmycar  Icon User is offline

  • D.I.C Regular

Reputation: 86
  • View blog
  • Posts: 390
  • Joined: 29-August 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 10:51 AM

View Postjhar131, on 31 August 2010 - 09:29 AM, said:

Some places online say that you can't add an element to an array in java. My instructor says differently. My code looks like this:


You cannot add on to an array. However, lets say you need 10 spots in an array so you make an array size 15. The last 5 spots have nothing and therefore you can "add" on later if need be, but you can never make that array size 16. You can remake the array and update the size.
Was This Post Helpful? 0
  • +
  • -

#4 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 11:02 AM

Ok, so I changed the code so that H = size -1; but I am still going out of bounds. And I am not trying to resize the array. The array has 30 spots, and only 20 are filled. Still tooling around with it.
Was This Post Helpful? 0
  • +
  • -

#5 ipushmycar  Icon User is offline

  • D.I.C Regular

Reputation: 86
  • View blog
  • Posts: 390
  • Joined: 29-August 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 11:08 AM

What are you trying to do with your program?
Was This Post Helpful? 0
  • +
  • -

#6 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 11:25 AM

I need to read from a file, load the file into an array of objects, and allow the user to print one, print all, update, add and delete the arrays. Everything works except for add.
Was This Post Helpful? 0
  • +
  • -

#7 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3101
  • View blog
  • Posts: 19,141
  • Joined: 14-September 07

Re: Adding an Element to an Array

Posted 31 August 2010 - 11:28 AM

Can you post the relevant snippets?


Are you storing data from the file in the array linearly? Your current for loop is just shifting all of the elements, presumptively to make room for the new info coming from the file.
Was This Post Helpful? 0
  • +
  • -

#8 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 11:53 AM

View PostKYA, on 31 August 2010 - 10:28 AM, said:

Can you post the relevant snippets?


Are you storing data from the file in the array linearly? Your current for loop is just shifting all of the elements, presumptively to make room for the new info coming from the file.

No problem.

My main:
public class prog1
{
   public static void main(String[] args) throws IOException
   {
          final int MAXR = 30; //constant size of rows

          Student data[]; //an array of records of class Student

          double gpa;       //student's overall gpa

          int  choice,     //user menu selection
               hours,      //amount of hours carried by student
               size,          //counter loop for rows
               ID,         //employee ID number
               option = 0; //declartion of user option

          String first,    //student's first name
                 last,     //student's last name
                 name,     //array of complete names
                 year;     //the student's classification


          //create an array of correct type with constant size
          data = new Student[MAXR];

          //create an Student object at all
          Student all;

          //create decimal format object
          DecimalFormat formatter = new DecimalFormat("#0.00");
          //create a scanner object for file input
          File input = new File("stud.data");
          Scanner stud = new Scanner(input);

          //initalize counter
          size = 0;

          //populate arrays with file info
          while(stud.hasNext())
          {
            ID = stud.nextInt();
            first = stud.next();
            last = stud.next();
            name = last.concat(", ")+(first);
            year = stud.next();
            hours = stud.nextInt();
            gpa = stud.nextDouble();
            data[size] = new Student(ID,name,year,hours,gpa);
            size = size + 1;
          }

          //close the input file
          stud.close();

          //declare an Student object at all
          all = new Student();



Skipping some irrelevant parts.....

the start of my class:

public class Student
{
   final int MAXR = 30; //declare row size as constant

         int ID1,    //declare student ID for class
             hours1; //declare student hours for class

         double gpa1; //declare student gpa for class

        String name1,    //declare employee name for class
               year1;    //declare product number for class


        public Student()
        {
          ID1 = 0;
          name1 = "0";
          year1 = "0";
          hours1 = 0;
          gpa1 = 0.00;
        }


/*  Purpose: This method will assign the variables value.
    Precondition: An array of class objects with variable value zero.
    Postcondtion: An array of class objects with variable values that
                  have been assigned to it from the main.*/

    public Student(int ID, String name, String year, int hours,
    double gpa)
    {
       ID1 = ID;
       name1 = name;
       year1 = year;
       hours1 = hours;
       gpa1 = gpa;
    }




and the add record method:

     public void AddRec(Student data[],int size)
     {
         int newhours, //declare student hours for class
             newID,
             key,
             H,
             I;

         double newgpa; //declare student gpa for class

         String newyear,
                newname,
                newfirst,
                newlast;

         Student newb;

           SortRecordsid(data,size);

           System.out.println("Enter the ID number of the new student:");
           System.out.println("Ex: 2190");

           Scanner keyboard = new Scanner(System.in);
           key = keyboard.nextInt();

           I= BinSearch(data,key,size);

           if(I == -1)
           {

                   newID = key;


                System.out.println();
                System.out.println();
                System.out.println("Please enter the last name of the new student:");
                System.out.println("Ex: Doe");
                System.out.println();

                   newlast = keyboard.next();

                System.out.println();
                System.out.println();
                System.out.println("Please enter the first name of the new student:");
                System.out.println("Ex: Jane");
                System.out.println();

                   newfirst = keyboard.next();

                   newname = newlast.concat(", ")+(newfirst);

                System.out.println();
                System.out.println();
                System.out.println("Please enter the new student's classification");
                System.out.println("Ex: freshman");
                System.out.println();

                   newyear = keyboard.next();


                System.out.println();
                System.out.println();
                System.out.println("Please enter the new student's hours");
                System.out.println("Ex: 45");
                System.out.println();

                   newhours = keyboard.nextInt();

                System.out.println();
                System.out.println();
                System.out.println("Please enter the new student's GPA");
                System.out.println("Ex: 2.6");
                System.out.println();

                System.out.println();

                   newgpa = keyboard.nextDouble();

                   newb = new Student(newID,newname,newyear,newhours,newgpa);

                     if(size < data.length)
                      for(H = size; H > I; H--)
                       {
                           data[H] = data[H-1];
                       }
                         data[I+1] = newb;
                         size++;


            }
            else
            {
              System.out.printf("%8d",key, " already has student records.");
              System.out.println();
            }
        }




Sorry for the extra code in the add record method, I just wanted you to see it all.

Is it possible that when I pass the array from main to class, the 10 null spaces in the array are just chopped off? Does that happen?
Was This Post Helpful? 0
  • +
  • -

#9 ipushmycar  Icon User is offline

  • D.I.C Regular

Reputation: 86
  • View blog
  • Posts: 390
  • Joined: 29-August 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 02:18 PM

Well IMO there are two different ways you could write your add method. It depends on how you wrote delete. Way one: delete only deletes the last on the array (best running time). -OR- Way two: The user can select to delete one element from 0 to your array.length. (worst running time of O(n)).

This is what I would do or something similar.

Way one:

int count; //holds the number of valid spots in the array
for(int i = 0; i < array.length; i++)
{
    if(array[i] > -1) //-1 would mean the spot is not filled yet
    {
        count++;
    }
}

if(count >= array.length)
error//put your error here or you could make a new array copy everything over and add one!
else
array[count + 1] = whatever you need here;



Way two:
for(int i = 0; i < array.length; i++)
{
if(array[i] == -1)
{
   array[i] = whatever you need here;
   break;
}
else
error// or like above you could make a new array make it a longer length and copy everything over.
}



Hope this is what you meant and it helps!

This post has been edited by ipushmycar: 31 August 2010 - 02:25 PM

Was This Post Helpful? 0
  • +
  • -

#10 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • Joined: 15-July 08

Re: Adding an Element to an Array

Posted 31 August 2010 - 03:21 PM

If you can use the API here, I would.... There is a very nice method called Arrays.copyOf(). It takes two arguments, the array and the new length.

int[] a = new int[15];
... fill up array ...
a = Arrays.copyOf(a, 20);
... Now you have 5 more spots...


Was This Post Helpful? 0
  • +
  • -

#11 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 03:22 PM

First of all, thank you for the response. I coded your first message, and I am not going out of bounds. However, I am only getting the error message now. this leads me to believe as I said that the null spaces in the array are being cut off when it is passed to the class. How do I maintain the null spaces when passing to class?
Was This Post Helpful? 0
  • +
  • -

#12 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 03:30 PM

Dogstopper... Thank you, but that is not allowed with this program. It is my second semester of software engineering and I must create my own methods, I am not allowed to use built in functionality.
Was This Post Helpful? 0
  • +
  • -

#13 jhar131  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 149
  • Joined: 03-February 10

Re: Adding an Element to an Array

Posted 31 August 2010 - 06:23 PM

So I figured it out. Just in case any young software engineering student does a google search and happens upon this thread, my problem was with my position indicator.

I have a binary search implemented into the add, as you should only be able to add a record that doesn't already exist. Well, the "not found" return value is -1. I was attempting to use this in this line:
	                 for(H = size; H > I; H--)



line 82

all that needed changing was:
                         for(H = size -1; H >=0; H--)



Once again; thanks to everyone who offered help in this thread. This is a great community. Hopefully soon I will be more of a helper than a helpee. :smartass:
Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8329
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Adding an Element to an Array

Posted 31 August 2010 - 06:38 PM

View Postjhar131, on 31 August 2010 - 07:23 PM, said:

So I figured it out. Just in case any young software engineering student does a google search and happens upon this thread, my problem was with my position indicator.

I have a binary search implemented into the add, as you should only be able to add a record that doesn't already exist. Well, the "not found" return value is -1. I was attempting to use this in this line:
	                 for(H = size; H > I; H--)



line 82

all that needed changing was:
                         for(H = size -1; H >=0; H--)



Once again; thanks to everyone who offered help in this thread. This is a great community. Hopefully soon I will be more of a helper than a helpee. :smartass:

don't see why you do it by reverse

// returns an int array with N elements more than the original
int[] add(int[] orig, int increment) {
    int x[] = new int[orig.length + increment];
    for(int i = 0; i < orig.length; i++)
      x[i] = orig[i];
    return x;
}

void method() {
   int x[] = new int[10];
   x[0] = 5;
   x[5] = 50;

   x = add(x, 5);
   // x has now a lenght of 15
   // x[0] through x[9] have the original values
   // x[10] though x[14] contains 0
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1