【发布时间】:2012-11-02 12:53:17
【问题描述】:
到目前为止,如果我尝试使用 concat 运算符,我会收到此错误 Tester.java:14:找不到符号 符号:方法 concat(MyString) 位置:MyString 类 System.out.println(hello.concat(再见)); // 打印“hellogoodbye”
当我尝试打印 MyString 的“hello”对象时,我得到了 MyString@558ee9d6 我觉得它离工作太近了..
public class MyString
{
private char[] charString;
private String oneString;
public MyString(String string)
{
this.oneString = string;
}
//second constructor for overloading
public MyString(char[] s)
{
this.charString = s;
this.oneString = charString.toString();
}
//methods
public String toString( char [] s)
{
return new String(s);
}
public char charAt(int i) {
char [] temp = new char[oneString.length()];
for ( int j = 0; j < oneString.length() ; j++)
temp[j] = oneString.charAt(i);
return temp[i];
}
public String concat ( char[] s)
{
s.toString();
String result = oneString + s;
return result;
}
public String concat ( String s)
{
String result = oneString + s;
return result;
}
}
公共类测试员 { public static void main (String[] args)
{
MyString hello = new MyString("hello");
System.out.println(hello); // right now this prints MyString@558ee9d6
System.out.println(hello.charAt(0)); // works, prints 'h'
char[] arr = {'g','o','o','d','b','y','e' };
MyString goodbye = new MyString(arr);
// System.out.println(hello.concat(goodbye)); // i can't get this line to work
System.out.println(hello.equals(goodbye)); // works, prints false
System.out.println(hello.equals(hello)); //works, prints true
}
}
【问题讨论】:
-
你应该在发布之前稍微校对你的代码。一个简单的编译可以帮助你解决很多问题。
-
内部
charString是必需的吗?它只是让你的内部状态复杂化,只保留一个String会更简单。