为什么toString()为Java中的相同输入返回不同的值?

时间:2012-05-02 10:59:48

标签: java tostring

我正在编写一个GUI程序,它有JPasswordField来接收用户的文本。然后我将此值转换为字符串,方法如下:

 char[] pass = txtPass.getPassword(); //where txtPass is the JPasswordField
 System.out.println("Password:");
 ////////////////Check password/////
 for (int i=0; i< pass.length; i++)
    System.out.println(pass[i]);

 System.out.println("String pass"+ pass.toString());

但是,我执行应用程序的所有内容,我将收到pass.toString()的不同。我希望它们是独一无二的,这样我就可以做更多的哭泣函数。

4 个答案:

答案 0 :(得分:2)

尝试

System.out.println( "String pass: " + new String( pass ) );

对于非常大的指数,通过平方使用指数 - http://en.wikipedia.org/wiki/Exponentiation_by_squaring

答案 1 :(得分:1)

数组上的toString函数将返回数组中的字符。试试这个:

char[] pass = txtPass.getPassword(); //where txtPass is the JPasswordField
 System.out.println("Password:");
 ////////////////Check password/////
 for (int i=0; i< pass.length; i++)
    System.out.println(pass[i]);

 System.out.println("String pass"+ new String(pass));

这将创建一个包含数组中字符的新字符串。

答案 2 :(得分:0)

只需阅读Java SDK API,它就会非常清楚地说明,

另见toString of JPasswordField

public String toString(){return getClass()。getName()+“[”+ paramString()+“]”;}

toString方法返回整个Swing组件的toString,因此getClass()。getName()+ paramString()。而getPassword方法返回已键入组件密码字段的实际密码。

答案 3 :(得分:0)

而不是

System.out.println(“String pass”+ pass.toString());

你可以使用

System.out.println("String pass"+ String.valueOf(pass));

哪个适合您的要求。