0

I have an array containing elements, each having 3 parameters (int, float and string). I followed the explanations to print an array using the toString method but I get the error "the method must return a result of type String" at this line:

public String MyObject(int a, float b, String c) 

Here is my code:

public class MyObject 
{
  public int a;
  public float b;
  public String c;

  public String MyObject(int a, float b, String c) 
  {
    this.a = a;
    this.b = b;
    this.c = c;
  } 

  @Override
    public String toString()
  {
    return ("a="+a+" b="+b+" c="+c);
  }
}


ArrayList<MyObject> myArrayList = new ArrayList<MyObject>();

void setup() 
{
  size(100, 60);
  myArrayList.add(new MyObject(1, 4.5, "a"));
  myArrayList.add(new MyObject(2, 5.8, "b"));
  myArrayList.add(new MyObject(3, 1.3, "c"));
  System.out.println(myArrayList);
  myArrayList.removeAll(myArrayList);
}

I don't understand why I get this error since the toString method writes out the int and the float.

Could anyone give me a hint on how to solve this ?

Thanks for your help

Graham Slick
  • 6,692
  • 9
  • 51
  • 87

3 Answers3

4

The constructor cannot have a return type. It should be defined as:

public MyObject(int a, float b, String c) {
  doSomething();
}
injecteer
  • 20,038
  • 4
  • 45
  • 89
4

As pointed out by the comment, you don't have a valid constructor right now.

public String MyObject(int a, float b, String c) {
  this.a = a;
  this.b = b;
  this.c = c;
} 

is a method with return type String called MyObject. The error you are seeing is that you've declared the method to have a return type String, but the method as you've written it doesn't return anything.

Moreover, because you haven't defined a constructor, Java adds the default constructor for you:

public MyObject(){

}

Thus, when you try to construct a MyObject with the three given arguments: new MyObject(3, 1.3, "c");, it's not finding a matching constructor.

Change the method to:

public MyObject(int a, float b, String c) {
  this.a = a;
  this.b = b;
  this.c = c;
} 

And it should work.

Mshnik
  • 7,032
  • 1
  • 25
  • 38
3

Your constructor doesn't follow the correct semantic. It should have same name as Class Name and no return type. i.e.

public MyObject(int a, float b, String c){

}
Gaurav
  • 299
  • 2
  • 10