2017-07-02 67 views
-1

我初始化了一個Password對象,並且在爲計算字符串中的字母數量等後期目的而將同一對象用作字符串時遇到了問題。我知道我只能通過方法String.valueOf.toString獲取對象的文本表示。我如何去取得我的對象傳遞,並獲得我初始化它的「你好」字符串?將實例化對象轉換爲字符串

public class Password { 

public Password (String text) { 
} 

public String getText(){ 
    String string = String.valueOf(this); 
    return string; 
} 
public static void main (String[] args) { 
    Password pass = new Password ("hello"); 
    System.out.println(pass.toString()); 
} 

}

+0

覆蓋了'的toString()'方法,並返回所需的值。 –

+1

https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html –

回答

0

您的實際getText()方法沒有意義:

public String getText(){ 
    String string = String.valueOf(this); 
    return string; 
} 

您嘗試重新從Password實例的toString()方法String
這真的沒有必要(無用的計算),它很笨拙,因爲toString()不是爲了提供功能數據而設計的。

爲了達到您的目標,這是非常基本的。

Store中Password實例的字段中的文本:

public Password (String text) { 
    this.text = text; 
} 

,並提供了text領域的看法。

你可以用這種方式取代getText()

public String getText(){  
    return text; 
} 
0

使用領域。

public class Password { 

    private String text; // This is a member (field) It belongs to each 
          // Password instance you create. 

    public Password(String value) { 
     this.text = value; // Copy the reference to the text to the field 
          // 'text' 
    } 
} 

String.valueOf(this)的問題,其中thisPassword實例,就是valueOf()方法完全沒有了如何將Password實例轉換爲場的想法. You named it "Password", but it could also be MYTEXT or MySecret . So you need to tell how a密碼instance can be displayed as text. In your case, you'll need to just use the從text`場上述例子。

你一定要閱讀docs about classes。我認爲你錯過了一些基本的東西。


注意:您也永遠不應該密碼存儲到一個字符串,因爲安全隱患,但是這完全是另外一個故事,超越你的問題的範圍。