java中的toString方法如何
好的,我已经完成了Java代码,我的老师希望我实现一个toString()方法,如下所述java中的toString方法如何,java,Java,好的,我已经完成了Java代码,我的老师希望我实现一个toString()方法,如下所述 您需要在GuessLogic类中提供一个toString方法,该方法将GuessLogic对象(即其所有成员变量)的状态作为单个字符串返回 我创建了GuessLogic类作为 int GuessLogic; GuessLogic = (int) (Math.random() * 10 + 1); 然后我尝试System.out.println(GuessLogic.toString()),因为我认为它是
您需要在GuessLogic类中提供一个toString方法,该方法将GuessLogic对象(即其所有成员变量)的状态作为单个字符串返回 我创建了GuessLogic类作为
int GuessLogic;
GuessLogic = (int) (Math.random() * 10 + 1);
然后我尝试System.out.println(GuessLogic.toString()),因为我认为它是这样工作的,但很明显我不理解某些东西。非常感谢。int GuessLogic是一种基本类型,不是对象,因此没有任何方法。您应该使用Integer对象或Integer.toString静态方法
Integer.toString(GuessLogic)
我发现你的要求有点含糊不清,但是如果你需要一个类的toString方法,你可以尝试为我的Photo类制作如下示例:
@Override
public String toString() {
return "Photo{" +
"id=" + id +
", user_id=" + user_id +
", imageable_type='" + imageable_type + '\'' +
", imageable_id=" + imageable_id +
", image_path='" + image_path + '\'' +
", description='" + description + '\'' +
", metadata='" + metadata + '\'' +
", wind='" + wind + '\'' +
'}';
}
您刚刚定义了一个变量,它来自于基本类型
int
,因此您可以调用toString()
或为其生成方法
要定义类,必须执行以下操作:
public class GuessLogic {
private int guessLogicVariable;
public GuessLogic(int guessLogicVariable) {
this.guessLogicVariable = guessLogicVariable;
}
public String toString() {
return "GuessLogic{" +
"guessLogicVariable=" + guessLogicVariable +
'}';
}
}
然后,您可以在主方法中或任何需要的地方使用该类,如下所示:
public final void main(String args[]){
GuessLogic guessLogic = new GuessLogic(10);
System.out.println(guessLogic.toString());
}
这不是一门课。这是一个变量。如果需要,我可以发布整个代码。如果我要求的内容不清楚,在创建类之后,您可以使用IDE生成
toString()
方法。我不认为这不清楚,只是错了。你的代码中有类猜测逻辑{
这一行吗?@Serph:你的要求很清楚,你想在类上实现一个名为.toString()
的方法。但要做到这一点,你首先需要一个类。“你要在你的猜测逻辑类中提供一个toString方法”
public final void main(String args[]){
GuessLogic guessLogic = new GuessLogic(10);
System.out.println(guessLogic.toString());
}