【问题标题】:tostring method giving wrong outputtostring 方法给出错误的输出
【发布时间】:2014-05-08 07:51:15
【问题描述】:

您好,我正在编写一个测试程序来反转字符串。当我使用 toString() 方法将字符数组转换为字符串时,我得到了错误的输出。当我尝试使用 for 循环手动打印数组而不将其转换为字符串时,答案是正确的。我写的代码如下图:

import java.util.*;
public class stringManip {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String str = "This is a string";
    System.out.println("String=" +str);
    //reverse(s);

    char[] c = str.toCharArray();
    int left = 0;
    int right = str.length() - 1;
    for (int i = 0; i < (str.length())/2; i++)
    {
        char temp = c[left];
        c[left++] = c[right];
        c[right--] = temp;
    }
    System.out.print("Reverse="+c.toString());


    }
}

我应该得到我输入的字符串的反向,而不是得到的输出是:

String=This is a string

Reverse=[C@45a1472d

使用 toString() 方法时是否有问题?任何帮助表示赞赏。谢谢你。

【问题讨论】:

    标签: eclipse string tostring


    【解决方案1】:

    数组不会覆盖toString() 方法。因此,您看到的是默认 Object.toString() 实现的输出,其中包含对象的类型([C 表示字符数组),后跟其 hashCode。

    要从 char 数组构造字符串,请使用

    new String(c)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-06
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 2020-09-08
      • 2023-03-08
      • 2021-02-11
      相关资源
      最近更新 更多