0

I'm writing a program that is supposed to represent the receipt of a pet shop, and I have the user enter in specific attributes about what pet they want to buy. For one of my methods, I only want to display one of the pets the user has inputted. For some reason, I keep getting an array index out of bounds exception -1 and I just don't understand why.

 case 10: System.out.println();
                     String nameDisplay = umy.getS("Enter name of pet to display.");
                     umy.getReturn();
                     System.out.println();
                     int pos= list.linearSearch(nameDisplay);
                     list.displayOne(pos);
                     System.out.println();
                     break; //This is my calling of the methods in the driver

   public void display()
{
    for (int x=0; x<size; x++)
        System.out.println(petshopList[x].toString());
}//display

public void displayOne(int num)
{
    System.out.println(petshopList[num].toString());
}//display

I know I didn't include a lot of other things I have defined, but I believe my error is somewhere in one of the display methods. Thanks in advance for the help.

edit: Sorry, I should have included the linear search method.

    public int linearSearch(String value)
{
    int index=0;
    while(index<size && !(petshopList[index].getName()).equals(value))            
        index++;
    if (index<size)
        return index;
    else
        return -1;
}//linearSearch   

Also, here is the toString method.

 public String toString(){
    return name;
} //overridden method from object class 
my518
  • 1
  • 1
  • Why don't you first try printing the size in display() function and num in displayOne(int num) functions to know the values. They are the one's causing the exception. Then you can figure out the problem. Since your code is not complete, this is what I can say. – Sunil Dabburi May 22 '16 at 06:44
  • Can you share the code for `linearSearch` please? – Mureinik May 22 '16 at 06:45
  • Please post full code to provede a MCVE: http://stackoverflow.com/help/mcve – DVarga May 22 '16 at 06:46
  • Are you sure that your linearSearch method is returning a valid index – the.Doc May 22 '16 at 06:47

0 Answers0