0

With this code:

  public static void main(String[] args) {

    String s = "Java";
    StringBuilder buffer = new StringBuilder(s);
    change(buffer);

       System.out.println("What's strBuf.charAt(5)? " + strBuf.charAt(3));
       System.out.println(buffer);
  }

     private static void change(StringBuilder buffer) {

          buffer.append(" and HTML");
  }

When I run the code using StringBuilder I get error message

 The constructor StringBuilder(String) is undefined
    The method charAt(int) is undefined for the type StringBuilder

Tried StringBuffer instead and it works. The content of the StringBuffer object is compiled to "Java and Eclipse.."

  public static void main(String[] args) {

    String s = "Java";
    StringBuffer strbuf = new StringBuffer(s);
    change(strbuf);

               System.out.println("The Stringbuffer.charAt(5) is ? " + strbuf.charAt(3));
           System.out.println(strbuf);
 }

       private static void change(StringBuffer strbuf) {

                       strbuf.append(" and Eclipse");
 }

}

4

3 回答 3

5

StringBuilder 确实有一个接受 aString作为参数的构造函数,并且确实一个.charAt()方法(它必须实现它,因为它实现了CharSequence)。

结论:这是您的 IDE 部分的事故,它没有导入正确的StringBuilder. 您使用另一个库,该库具有不幸的“属性”,即实现了同名的类——但不在同一个包中。

如果导入行是,请查看文件顶部:

import java.lang.StringBuilder;
于 2013-06-18T15:50:11.947 回答
3

您可能导入了错误的 StringBuilder 类,而不是具有 StringBuilder(String) 构造函数和 charAt(int) 方法的 java.lang.StringBuilder。

你能检查你的进口吗?你应该有这个

import java.lang.StringBuilder;
于 2013-06-18T15:54:59.240 回答
0

确保您没有将您的班级名称定义为StringBuilder

例如:即使您正确导入它

 import java.lang.StringBuilder;

但是如果你把你的类写成

 public class StringBuilder { //If class name matches below Object Creation
 public static void main(String[] args) {

String s = "Java";
StringBuilder buffer = new StringBuilder(s);  //Object creation
change(buffer);

   System.out.println("What's strBuf.charAt(5)? " + strBuf.charAt(3));
   System.out.println(buffer);
}

 private static void change(StringBuilder buffer) {

      buffer.append(" and HTML"); //you will get this error at append
  //The method append(String) is undefined for the type StringBuilder
} 
}

建议

将您的班级名称重命名为其他名称,但不是 StringBuilder

于 2015-10-19T13:42:46.270 回答