2

Hi i try to make program who when will be compiled print X and Id arrays but i have a problem when i try add static int. I made this like on tutorial but it can't compile. Do you have any suggest?

class SetCord
{
   double x;
   double y;
   private  int Id;
   private static int NextId;

   public SetCord(double a, double b)
   {
      x=a;
      y=b;
   }

   public double getX()
   {
      return x;
      Id=NextId;
      NextId++;
   }

   public double getY()
   {
      return y;
      Id=NextId;
      NextId++;
   }

   public int getId()
   {
      return Id;
   }
}

class Test
{

   public static void main(String args[])
   { 
      SetCord[] teste = new SetCord[3];
      teste[0] = new SetCord(3, 5);
      teste[1] = new SetCord(5, 5);
      teste[2] = new SetCord(1, 2);

      for(SetCord x:teste)
      {
         System.out.println("give x" +  x.getX());
         System.out.println("give id" +  x.getId());
      }  
   }

   static
   {
      NextId=1;
   }
}

Thanks!

Falk Thiele
  • 4,424
  • 2
  • 17
  • 44
Brade
  • 17
  • 7
  • 'static { NextId=1; }' portion you can add on SetCord. It will help to solve your issue. You also need other tasks for getY and getX. That issue is already solved by others – SkyWalker Mar 11 '16 at 19:07

2 Answers2

2

There shouldn't be any statements post return in your method. Return should be the last statement of your method

LIKE THIS:

public double getX()
{
    Id=SetCord.NextId;
    SetCord.NextId++;
    return x;
}
public double getY()
{
    Id=SetCord.NextId;
    SetCord.NextId++;
    return y;
}
Sashi Kant
  • 13,277
  • 9
  • 44
  • 71
2

Statements after return cannot be reachable. For ex

public double getY()
{
    return y;
    Id=NextId;
    NextId++;
}

What ever business logic you want to do, do before the method return. You want to do ?

public double getY()
{        
    Id=NextId;
    NextId++;
   return y;
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307