我有一个包含元素的数组,每个元素都有 3 个参数(int、float 和 string)。我按照说明使用 toString 方法打印数组,但在这一行收到错误“该方法必须返回 String 类型的结果”:
public String MyObject(int a, float b, String c)
这是我的代码:
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);
}
我不明白为什么会收到此错误,因为 toString 方法写出了 int 和 float。
有人可以告诉我如何解决这个问题吗?
感谢您的帮助
最佳答案
正如评论所指出的,您现在没有有效的构造函数。
public String MyObject(int a, float b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
是一个名为 MyObject
的返回类型为 String
的方法。您看到的错误是您已声明该方法具有返回类型 String
,但您编写的方法不返回任何内容。
此外,由于您还没有定义构造函数,Java 会为您添加默认构造函数:
public MyObject(){
}
因此,当您尝试使用三个给定参数构造 MyObject
时:new MyObject(3, 1.3, "c");
,它找不到匹配的构造函数。
将方法更改为:
public MyObject(int a, float b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
它应该可以工作。
关于java - 使用toString方法打印ArrayList内容时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31395174/