我目前正在创建自己的“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/