SYED SAAD ALI
SYED SAAD ALI

Reputation: 77

method's return type is a specific object?

My question is i am creating a class which is reading data from the file and the data is

produce,3554,broccoli,5.99,1

produce,3554,broccoli,5.99,1

produce,3555,carrots,2.23,0.25

produce,3555,carrots,2.23,0.25

produce,3555,carrots,2.23,0.25

----------------------------------------------------// file ends

Product[] p= new Product[num];
int k=0;
try
{
   File f = new File("somefile.txt");
   Scanner s= new Scanner(f);
   while(s.hasNextLine())
   {
      String txt = s.nextLine();
      String[] field = txt.split(",");
      p[k] = new Product();//name,code,veg,price,unit are the variable and defined in theparent class named Product and toString method also

      p[k].name=field[0];
      p[k].code=field[1];
      p[k].veg=field[2];
      p[k].price=field[3];
      p[k].unit=field[4];
      k++;
   }

Now i want to create a method

  public static Product delete(int pos)
  {
      return p[pos]  // this will represent the toString representation of particular inde

  }

i am trying this code but this gives me an Exception that p[pos] is not defined

is there any other way out or method to get this method works returning in the form of

object

Upvotes: 2

Views: 94

Answers (3)

llamositopia
llamositopia

Reputation: 724

Your issue is that delete is static but p is not. Since static and non-static are separate and not interchangeable, the delete method does not recognize it.

Upvotes: 0

Joel
Joel

Reputation: 5674

Your declaration of p is not visible in the static namespace. Either move it into the static namespace, or change the function to be not static.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

You likely have a scoping issue. I'm guessing that your p Product array is declared inside of a method or constructor and if so, is visible only inside of that method or constructor. If you want to use the p array in more than one method, it should be declared in the class not in a method or constructor.

Upvotes: 1

Related Questions