java - 创建自己的String类,系统首先打印出null

标签 java

我目前正在创建自己的“String”类。

这是我的程序...不会包含所有内容,但至少包含可以帮助您测试的内容。

public class MyString {

private char [] string;
public int counter = 0;

public MyString(char [] chars)
{
    this.string = chars;
//I added this extra method here to show you the current stuff in char.(no null was there)
    try{
        for(int i = 0;; i++){
            System.out.print(string[i]);
            counter++;
        }
    }
    catch (Exception e){
        System.out.println();
    }
}



public MyString toLowerCase() {
    char [] temp = new char [counter];
    for(int i = 0; i < length(); i++)
    {
        if(string[i] < 91 && string[i] > 64)
            temp[i] = (char) (string[i] + 32);
        else
            temp[i] = string[i];
    }

    MyString s = new MyString(temp);

    return s; //prints the try method above again, no null
}
}

在一个具有主要功能的类上...

public class temp {

public static void main(String[] args) {

char [] str2 = new char [5];
    str2[0] = 'H';
    str2[1] = 'E';
    str2[2] = 'l';
    str2[3] = 'l';
    str2[4] = 'O';

MyString s = new MyString(str2);

System.out.println(s.toLowerCase()); //null came out from here..
}
}

这段代码的输出是...

HEllO
hello
nullhello

如您所见,它以 null 开头。我想知道是什么导致了这样的问题。正如您所看到的,我在构造函数中添加了一个 try 方法来测试字符数组。那里没有空值。直到我在主程序上使用它时,出现了 null。

最佳答案

System.out.println(s.toLowerCase());

将调用您的MyString类的toString方法。

根据您的输出,它可能看起来像这样(即您将一些内容附加到 null String):

public String toString ()
{
    String result = null;
    for (int i = 0; i < string.length; i++)
        result += string[i];
    return result;
}

这会在返回的String的开头添加一个null

更好的 toString 方法是:

public String toString ()
{
    return new String(string);
}

关于java - 创建自己的String类,系统首先打印出null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32836410/

相关文章:

java - 如何通过 eclipse 调试外部 .jar 文件?

java - 打印带有换行符的字符串

java - object 在java中构造一个对象类

java - 具有特定颜色的 JPanel 绘图

java - 绑定(bind)spring mvc命令对象时如何将多个参数名映射到POJO

java - XPages:如何将 Java 日期值放入 ObjectObject 中

java - android解析json,删除和插入值到数据库

java - @ExceptionHandler 不适用于特定的 hibernate 异常

java - 使用 Key.Id 查询 Google App Engine 数据存储

java - 数据源中的 NPE