?
Solved

An array to store a list of items

Posted on 2004-11-18
23
Medium Priority
?
292 Views
Last Modified: 2010-03-31
I am trying to create a class use a 10 element array to store string data like a list. I want to do several things with it, I've commented the problem spots of the code and the objectives of each method maybe someone can help me work out the bugs in them. Don't assume just because I havent marked errors in a particular segment that it's correct. I havent been able to get it to compile to test or written a test harness yet.


public class List {
public int num; //a variable to store the number of names in the list

String[] item = new String[10]; //need a 10 item array called item that holds string data
    public List (item); //major problems, possibly line above too - supposed to be a constructor
                             //that creates a list array with no items in the list
                             //see footnote after code for a list of errors associated with this segment

public String deleteItem(){   //removes the first item in the list (item[0] and moves
      return item[0];             //all other items up by one position
      for(int i=1; i<item.length; i++)
         item[i]=item[i+1];
}

public boolean enterList(String name){  //adds an item to the back of the list and returns true if
       if(list[10!=null)                            //successful. if the list is full it returns false and does not
           return false;                           //alter the list in any way
       else
            customer[num+1]=name;
}

public int numberinList(){               //returns the number of items on the list
     for(int i=0; i<list.length; i++)
          if(list[i]!=null)
              num = num + 1;
           else
              num = num;
}

public boolean isEmpty(){       //returns true if there are no items on the list
         if(list[0]==null)
            return true;
}

public boolean isFull(){         //returns true if the list is full
        if(list[10]!=null)
             return true;
}

public String toString(){      //returns a list of items in the format: "apple, banana, pear"
      for(int i=0; i<list.length-1; i++)  
          reutrn list[i] + ", ";
     for(int i=list.length-1; i<list.length; i++)
          return list[i];       //to get the last item without a trailing comma
}

}//List Class


Footnote:
<identifier> expected
'(' expected
cannot resolve symbol "item"
missing method body, or declare abstract

The constructor method all four errors are associated with should simply create a List object that has no items on the list. However I know my syntax is horribly wrong and I can't for the life of me get it right.

I would also like to know if the other methods I have set will work as they are intended of if I have made mistakes in them.
0
Comment
Question by:Wraith10
  • 13
  • 6
  • 3
  • +1
23 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 12612384
First remark: don't call your class List (that class name exists already twice in java).
Call it MyList or soemthing like that.
0
 
LVL 35

Expert Comment

by:girionis
ID: 12612398
>  public List (item);

The above is a wrong syntax. You need to do

public List(String [] item)
{
    this.item = item;
}

> return item[0];

Return should be at the end of the method otherwise you will get a compile time error about unreachable code (if I remember correctly).

> reutrn list[i] + ", ";


You cannot do that (see above comment). You will have to hold all of your items in a separate variable and return that variabel at the end of the processing, something like

StringBuffer sb = new StringBuffer();
for (int i=0; i<list.length-1; i++)
{
   sb.append(list[i] + ", ");
}
sb.append(list[i]);
return sb.toString();
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612412
What about

public class MyList {

      private int num; //a variable to store the number of names in the list
      private String[] item = new String[10]; //need a 10 item array called item that holds string data

      public MyList () {
      }

      public String deleteItem() {   //removes the first item in the list (item[0] and moves
           if (isEmpty())
              return null;
           String firstItem = item[0];                //all other items up by one position
           for(int i=1; i<num; i++)
              item[i]=item[i+1];
           return firstItem;
      }

      public boolean enterList(String name) {  //adds an item to the back of the list and returns true if
          if (num==10)                                   //successful. if the list is full it returns false and does not
                return false;                              //alter the list in any way
          customer[num+1]=name;
          num++;            
       }

       public int numberinList()  {               //returns the number of items on the list
           return num;
       }

       public boolean isEmpty(){       //returns true if there are no items on the list
          return (num==0);
       }

       public boolean isFull(){         //returns true if the list is full
          return (num==10);
       }

       public String toString(){      //returns a list of items in the format: "apple, banana, pear"
          StringBuffer output = new StringBuffer();

          for(int i=0; i<num-2; i++)  
             output.append( item[i] + "," );
          output.append( item[num-1]);
          return output.toString();
      }

} //List Class
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 37

Expert Comment

by:zzynx
ID: 12612423
1) >> I am trying to create a class use a 10 element array to store string data like a list.

2) >> supposed to be a constructor that creates a list array with no items in the list
A list array? In 1) you say you want to work with an array?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612467
Some comment (and corrections) on my proposal:

public class MyList {

      private int num;                                      //a variable to store the number of names in the list (initially 0)
      private String[] item = new String[10];     // holds the (maximum) 10 strings in item[0] to item[9]

      public MyList () {            // This creates just an empty MyList, since num=0
      }

      public String deleteItem() {   //removes the first item in the list (item[0] and moves
           if (isEmpty())
              return null;                             // You can't return the first item if there is no first item ;°)

           String firstItem = item[0];          // Remember that first item
           for(int i=1; i<num; i++)             // shift the others one position
              item[i-1]=item[i];                   // remark the indices where wrong (also in my first post)
           num--;                                     // You have to decrement the number of items.  This was forgotten (also in my first post)!!!!
           return firstItem;
      }

      public boolean enterList(String name) {  
          if (isFull())                            // better than if (num==10)
                return false;        
          item[num+1]=name;             // replaced "customer" by "item"
          num++;                               // increment the number of items
          return true;                           // was previously forgotten
       }

       public int numberinList()  {      //returns the number of items on the list       (Better name this function getSize() or something like that)
           return num;
       }

       public boolean isEmpty(){       //returns true if there are no items on the list
          return (num==0);
       }

       public boolean isFull(){         //returns true if the list is full
          return (num==10);
       }

       public String toString(){      //returns a list of items in the format: "apple, banana, pear"
          StringBuffer output = new StringBuffer();

          for(int i=0; i<num-2; i++)  
             output.append( item[i] + "," );
          output.append( item[num-1]);
          return output.toString();
      }

      // Don't you need this?
      public String getItem(int index) {
          if ( index >= num )
            return null;
          return item[index];
      }

} //MyList Class
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612487
To test add this function to the MyList class:

public static void main(String[] args) {
     MyList myList = new MyList();

     myList.enterList("Item 1");
     myList.enterList("Item 2");
     myList.enterList("Item 3");
     myList.enterList("Item 4");
     myList.enterList("Item 5");
     System.out.println("# items: " + myList.numberinList() );
     System.out.println("Content: " + myList.toString() );

     System.out.println("Deleted: " + myList.deleteItem() );    
     System.out.println("# items: " + myList.numberinList() );
     System.out.println("Content: " + myList.toString() );

     System.out.println("2nd item: " + myList.get(1) );
}
0
 
LVL 3

Expert Comment

by:vikraman_b
ID: 12612614
HI
Have a look to get a throw idea of List
public final class List
{

    public List(Object obj, List list)
    {
        tail = list;
        head = obj;
    }

    public List()
    {
        this(null, null);
    }

    public static List make()
    {
        return new List();
    }

    public static List make(Object obj)
    {
        return new List(obj, new List());
    }

    public static List make(Object obj, Object obj1)
    {
        return new List(obj, new List(obj1, new List()));
    }

    public static List make(Object obj, Object obj1, Object obj2)
    {
        return new List(obj, new List(obj1, new List(obj2, new List())));
    }

    public static List make(Object aobj[])
    {
        List list = new List();
        for(int i = aobj.length - 1; i >= 0; i--)
            list = new List(aobj[i], list);

        return list;
    }

    public static List make(int i, Object obj)
    {
        List list = new List();
        for(int j = 0; j < i; j++)
            list = new List(obj, list);

        return list;
    }

    public boolean isEmpty()
    {
        return tail == null;
    }

    public boolean nonEmpty()
    {
        return tail != null;
    }

    public int length()
    {
        List list = this;
        int i;
        for(i = 0; list.tail != null; i++)
            list = list.tail;

        return i;
    }

    public List prepend(Object obj)
    {
        return new List(obj, this);
    }

    public List prependList(List list)
    {
        if(isEmpty())
            return list;
        if(list.isEmpty())
            return this;
        List list1 = this;
        for(list = list.reverse(); list.nonEmpty();)
        {
            List list2 = list;
            list = list.tail;
            list2.tail = list1;
            list1 = list2;
        }

        return list1;
    }

    public List reverse()
    {
        List list = new List();
        for(List list1 = this; list1.nonEmpty(); list1 = list1.tail)
            list = new List(list1.head, list);

        return list;
    }

    public List append(Object obj)
    {
        return make(obj).prependList(this);
    }

    public List appendList(List list)
    {
        return list.prependList(this);
    }

    public Object[] toArray(Object aobj[])
    {
        int i = 0;
        for(List list = this; list.nonEmpty() && i < aobj.length; i++)
        {
            aobj[i] = list.head;
            list = list.tail;
        }

        return aobj;
    }

    public String toString(String s)
    {
        if(isEmpty())
            return "";
        StringBuffer stringbuffer = new StringBuffer();
        stringbuffer.append(head.toString());
        for(List list = tail; list.nonEmpty(); list = list.tail)
        {
            stringbuffer.append(s);
            stringbuffer.append(list.head.toString());
        }

        return stringbuffer.toString();
    }

    public String toString()
    {
        return toString(",");
    }

    public int hashCode()
    {
        List list = this;
        int i = 0;
        for(; list.tail != null; list = list.tail)
            i = i * 41 + (head == null ? 0 : head.hashCode());

        return i;
    }

    public boolean equals(Object obj)
    {
        return (obj instanceof List) && equals(this, (List)obj);
    }

    public static boolean equals(List list, List list1)
    {
        for(; list.tail != null && list1.tail != null; list1 = list1.tail)
        {
            if(list.head == null)
            {
                if(list1.head != null)
                    return false;
            } else
            if(!list.head.equals(list1.head))
                return false;
            list = list.tail;
        }

        return list.tail == null && list1.tail == null;
    }

    public boolean contains(Object obj)
    {
        for(List list = this; list.tail != null; list = list.tail)
            if(obj == null)
            {
                if(list.head == null)
                    return true;
            } else
            if(obj.equals(list.head))
                return true;

        return false;
    }

    public Object last()
    {
        Object obj = null;
        for(List list = this; list.tail != null; list = list.tail)
            obj = list.head;

        return obj;
    }

    public Object head;
    public List tail;
}
0
 

Author Comment

by:Wraith10
ID: 12612701
For the boolean methods to return if the list is empty or full would they return true or are they simply setting num to a specified value? I am not too familiar with how booleans work. I want them to test IF the list is full and if it is return true not simply set the list to full. Etc. Apologies if your code does that I just want to clarify.


Current errors are as follows:
missing method body or declare abstract
>public LineUp (String[]customer);

cannot resolve symbol
>output.append(customer[i] + ",");

cannot resolve symbol
>output.append(customer[num-1]);

cannot resolve symbol
>return output.toString();

Full version of the current code: (some names changed)
public class LineUp {
    private int num;
    public int getNum() { return num; }
   
    String[] customer = new String[10];
    public LineUp (String[]customer); // would this correctly create a new blank lineup item?

   public String servePerson(){
     if(isEmpty()) //would I still be able to say if(num==0) instead?
        return null;
     else
        return customer[0];     // I want it to return the person at the front of the
    for(int i=1; i<num; i++)   //line BEFORE it is changed
          customer[i-1]=customer[i];
     num--;
}

public boolean enterLineUp(String name)[
     if(isFull())  //would it also work to continue saying if(num==10) it makes more sense to me
         return false;
     customer[num+1]=name; //should this be an else?
     num++;
     return true;
}

public int NumberInLine(){
      return num; //perhaps this should be something else since num is never
                        //defined within the class or how would I define num?
}

public boolean isEmpty(){
      return (num==0); //brackets needed?
} //does it set num to 0 or CHECK if it is 0. I want it to check not set

public boolean isFull(){
      return(num==10); // see above method for comments
}

public String toString(){
      for(int i=0, i<num-2; i++)
      output.append(customer[i] + ", ";
      output.append(customer[num-1]);
      return output.toString();
}

}
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612739
>>  I want them to test IF the list is full and if it is return true not simply set the list to full.
That's exactly what these do:

       public boolean isEmpty(){       //returns true if there are no items on the list
          return (num==0);       // returns true if num==0 and false otherwise
       }

       public boolean isFull(){         //returns true if the list is full
          return (num==10);    // returns true if num==10 and false otherwise
       }
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612745
num=0 is setting num to 0
num==0 is checking if num is 0 or not
0
 
LVL 35

Expert Comment

by:girionis
ID: 12612766
> For the boolean methods to return if the list is empty or full would
> they return true or are they simply setting num to a specified value?

They should return true or false. You do not care abotu the number of the elements, you just care about the emptyness or not of the list.

>  am not too familiar with how booleans work. I want them to test IF
> the list is full and if it is return true not simply set the list to
> full. Etc. Apologies if your code does that I just want to clarify.

Your code (following) does exactly that.

public boolean isFull(){
      return(num==10); // see above method for comments
}

> public LineUp (String[]customer); // would this correctly create a new
> blank lineup item?


Nope, this is incorrect syntax you have there. You are missing the opening and closing brackets. You should do something like

public LineUp(String [] customer)
{
  ...
}

but the above will create an array. If you only need to create one item you will need to pass an item there (single String) not the whole array.

Move this inside the else block

> for(int i=1; i<num; i++)   //line BEFORE it is changed
>          customer[i-1]=customer[i];
>     num--;

else
{
     for(int i=1; i<num; i++)   //line BEFORE it is changed
          customer[i-1]=customer[i];
     num--;
     return customer[0];     // I want it to return the person at the front of the
}
0
 
LVL 35

Expert Comment

by:girionis
ID: 12612772
> if(isFull())  //would it also work to continue saying if(num==10) it
> makes more sense to me

You can use either but in my opinion better leave it as it is since later on you might need to make changes that can take place inside the isFull() method and therefore you wouldn't have to change all the lines that have num==10 but just a single method.
0
 
LVL 35

Assisted Solution

by:girionis
girionis earned 80 total points
ID: 12612795
> customer[num+1]=name; //should this be an else?

Nope, if it fails the code will be executed, if not it will not. No need for else since return exits the method and returns the flow to the caller.

> return num; //perhaps this should be something else since num is never
>                         //defined within the class or how would I define num?

You ned to define num somewhere, make it an instance variable, i.e. declare it inside your class and do not make it static.

> return (num==0); //brackets needed?
> } //does it set num to 0 or CHECK if it is 0. I want it to check not set

No brackets needed. That is the correct syntax. It *checks* if it is 0. If it is returns true, otherwise it returns false;

> return(num==10); // see above method for comments

Same here.
0
 

Author Comment

by:Wraith10
ID: 12612817
Okay I made the change moving that piece of code inside the else block.

I'm still not sure how my constructor should look.

String[] customer = new String[10];
    public LineUp (String[]customer){
}//should there be something inside these brackets?
0
 
LVL 37

Accepted Solution

by:
zzynx earned 420 total points
ID: 12612819
This is working. Just test it.

/*
 * LineUp.java
 *
 */

public class LineUp {
   
    private int num;
    private String[] customer = new String[10];
   
   
    public int getNum() {
        return num;
    }
   
    public LineUp () { // would this correctly create a new blank lineup item?
    }

   public String servePerson(){
     if(isEmpty()) //would I still be able to say if(num==0) instead?
        return null;
     
     String person = customer[0];
     for(int i=1; i<num; i++)
          customer[i-1]=customer[i];
     num--;
     return person;
   }

   public boolean enterLineUp(String name) {
     if(isFull())
         return false;
     customer[num]=name;  // index should be num!!!!!
     num++;
     return true;
   }

   public int NumberInLine(){
      return num; //perhaps this should be something else since num is never
                  //defined within the class or how would I define num?
   }

   public boolean isEmpty(){
      return (num==0);
   }

   public boolean isFull(){
      return(num==10);
   }

   public String toString(){
      StringBuffer output = new StringBuffer();
      for(int i=0; i<num-1; i++)      // <<<<<<< num-1 instead of num-2
          output.append(customer[i] + ", ");
      output.append(customer[num-1]);
      return output.toString();
   }
   
   public static void main(String[] args) {
     LineUp myList = new LineUp();

     myList.enterLineUp("Item 1");
     myList.enterLineUp("Item 2");
     myList.enterLineUp("Item 3");
     myList.enterLineUp("Item 4");
     myList.enterLineUp("Item 5");
     System.out.println("# items: " + myList.NumberInLine() );
     System.out.println("Content: " + myList.toString() );

     System.out.println("Deleted: " + myList.servePerson() );    
     System.out.println("# items: " + myList.NumberInLine() );
     System.out.println("Content: " + myList.toString() );
   }
}
0
 
LVL 35

Expert Comment

by:girionis
ID: 12612822
> String[] customer = new String[10];
>     public LineUp (String[]customer){
> }//should there be something inside these brackets?

It depends on what your you want the constructor to do. If you want to pass and initialize an array then you will need to assign the array passed to the array inside your class

String[] customer = new String[10];
    public LineUp (String[]customer){
       this.customer = customer;
}//should there be something inside these brackets?

Otherwise you can leave it empty.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612826
>>You can use either but in my opinion better leave it as it is since later on you might need to make changes that can take place inside the isFull() method
>> and therefore you wouldn't have to change all the lines that have num==10 but just a single method.
Exactly
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612837
>>This is working. Just test it.

It prints:

# items: 5
Content: Item 1, Item 2, Item 3, Item 4, Item 5
Deleted: Item 1
# items: 4
Content: Item 2, Item 3, Item 4, Item 5
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612849
>> if(isEmpty()) //would I still be able to say if(num==0) instead?

You could do that, but why shouldn't you use the function isEmpty()?
It perfectly says where it stands for. Good for the readability too.

Some more explanation about isEmpty()

Writing this:

   public boolean isEmpty(){
      return (num==0);
   }

is exactly the same as writing this:

   public boolean isEmpty(){
      if (num==0)
         return true;
      else
         return false;
   }

The first is just shorter.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12612946
>> I'm still not sure how my constructor should look.

public class LineUp {
   
    private int num;                                                // this line
    private String[] customer = new String[10];        // and this are "performed" whenever you create a new LineUp object
                                                                           // So initially you have an empty customer array and num is 0. What would you want more ;°)
                              // So:
    public LineUp () { // this is perfectly OK
    }


Maybe you could explicitely write

public class LineUp {
   
    private int num=0;         // <<<<<< for better readability (but the "= 0" is in fact obsolete. It is always 0 by default)
0
 

Author Comment

by:Wraith10
ID: 12612967
Ugh how people do things like this for a living I will never know. Thank you for your invaluable assistance once again.
0
 
LVL 35

Expert Comment

by:girionis
ID: 12612974
:)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12613025
Thanks
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn different types of Android Layout and some basics of an Android App.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month12 days, 17 hours left to enroll

578 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question