2016-03-04 60 views
-1

好吧,我完成了我的Java代码和我的老师希望我实现toString()方法的说明如下toString方法如何

你要在你的GuessLogic类提供一个toString方法将GuessLogic对象(即其所有成员变量)的状态作为单个字符串返回。

我创建了GuessLogic类作为

int GuessLogic; 
GuessLogic = (int) (Math.random() * 10 + 1); 

然后我试着为System.out.println(GuessLogic.toString()),因为这是我怎么想它的工作,但显然我很不理解的东西。提前非常多谢。

+0

这不是一类。这是一个变量。 –

+0

如果我要求的内容不明确,我可以发布整个代码 – Serph

+0

创建一个类后,可以使用IDE生成'toString()'方法。 –

回答

0

int GuessLogic是一个原始类型,而不是一个对象,所以它没有任何方法。您应该使用Integer对象或Integer.toString静态方法

Integer.toString(GuessLogic) 
+0

“您将在您的GuessLogic课程中提供toString方法” –

0

我觉得你问一个有点模糊,但如果你需要一个类的toString方法,你可以尝试做一些像这样的例子我照片类:

@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 + '\'' + 
      '}'; 
} 
0
public class GuessLogic 
{ 
    int value; 

    public void setValue(){ 
     value = (int) (Math.random() * 10 + 1); 
    } 

    @Override 
    public String toString(){ 
     return Integer.toString(value); 
    } 
} 


GuessLogic guessLogic = new GuessLogic() 
guessLogic.setValue(); 
String result = guessLogic.toString(); 
0

您刚才定义一个变量,并从类型int这是原始类型,所以你可以调用一个toString()也建立它的方法是。

要定义你必须做这样的事情类:

public class GuessLogic { 
    private int guessLogicVariable; 

    public GuessLogic(int guessLogicVariable) { 

     this.guessLogicVariable = guessLogicVariable; 
    } 

    public String toString() { 
     return "GuessLogic{" + 
       "guessLogicVariable=" + guessLogicVariable + 
       '}'; 
    } 
} 

然后你可以使用这个类在main方法或任何你需要的是这样的:

public final void main(String args[]){ 

     GuessLogic guessLogic = new GuessLogic(10); 
     System.out.println(guessLogic.toString()); 
    }