gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:08:56 25 4
gpt4 key购买 nike

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

在一个有 main 函数的类上...

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 方法来测试字符数组。那里没有空值。直到我在 main 上使用它,一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com