简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM