代码如下:
public class StringBufferDemo {
//setCharAt()方法练习
public void setCharAtDemo() {
StringBuffer sbt=new StringBuffer("learning");
System.out.println(sbt.setCharAt(0, 'L');//此行报错
}
//appen()方法练习
public void appendDemo() {
StringBuffer sbt=new StringBuffer("abc");
sbt.append("def");
System.out.println(sbt);
}
public void appendDemo2() {
StringBuffer sbt=new StringBuffer();
StringBuffer sbt1=sbt.append(true);
System.out.println(sbt1);
}
public void appendDemo3() {
StringBuffer sb=new StringBuffer();
String user="wrx";
String pwd="123";
sb.append("select * from userInfo where username=")
.append(user)
.append(" and pwd=")
.append(pwd);
System.out.println("append sqls:\n"+sb);
}
//delete()方法练习
public void deleteDemo() {
StringBuffer sbt=new StringBuffer("I like China");
System.out.println(sbt.deleteCharAt(3));
}
public void deleteDemo2() {
StringBuffer sbt=new StringBuffer("I have a great idea");
System.out.println(sbt.delete(0, 5));//包前不包后
}
//insert()方法练习
public void insertDemo() {
StringBuffer sbt=new StringBuffer("My name is ");
System.out.println(sbt.insert(11, "WRX"));
}
//reserve()方法联系
public void reserveDemo() {
StringBuffer sbt=new StringBuffer("1234567");
System.out.println(sbt.reverse());
}
//trimToSize()方法练习
public void trimToSizeDemo() {
StringBuffer sbt=new StringBuffer(" hahahah wowowowow ");
sbt.trimToSize();
System.out.println(sbt);
//此方法同 setCharAt()方法
}
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer s = new StringBuffer(128);//初始化一个长度为128B的空对象
s=new StringBuffer("abc");
//String和StringBuffer之间的转化
String ss="abc";
StringBuffer sb1=new StringBuffer("123");
StringBuffer sb2=new StringBuffer(ss);//String-->StringBuffer
String s1=sb1.toString();//返回对象的字符串形式 StringBuffer-->String
System.out.println(sb1);
System.out.println(sb2);
System.out.println(s1);
StringBufferDemo sbd=new StringBufferDemo();
sbd.appendDemo();
sbd.appendDemo2();
sbd.appendDemo3();
sbd.deleteDemo();
sbd.deleteDemo2();
sbd.insertDemo();
sbd.reserveDemo();
sbd.setCharAtDemo();
}
}
上述代码第5行报错
报错原因:The method println(boolean) in the type PrintStream is not applicable for the arguments (vboolean)方法不适用于参数(void)
解决办法:
查阅 java API 可知,常用的StringBuffer类的几种方法的返回类型如下:
方法 | 返回类型 |
---|---|
setCharAt() | void |
trimToSize() | viod |
reverse() | StringBuffer |
delete() | StringBuffer |
deleteCharAt() | StringBuffer |
insert() | StringBuffer |
所以说,println()的参数可以是基本数据类型,对象,集合,数组,String和StringBuffer类,但是不能是返回类型为void的函数