陕西榆林煤矿招聘信息:一个java程序题

来源:百度文库 编辑:杭州交通信息网 时间:2024/05/05 01:09:06
class B {public static StringBuffer changStr(StringBuffer str)
{ for(i=0;i<str.length();i++)
{char B=str.charAt(i);
if(B=='\n') str.setChar(i,'n') ;
else if(B=='\b') str.setCharAt(i,'b') ;
else if(B=='\r') str.setCharAt(i,'r') ;
else if(B=='\f') str.setCharAt(i,'f') ;
/*if(B='\\') str.setCharAt(i,'\') ;
if(B='\'') str.setCharAt(i,''') ;
if(B='\''') str.setCharAt(i,'''') ;*/
else ;} }
StringBuffer name="ni ni hao hao meimei";
String newname= changStr(name).toString();
public static void main(String[] args){System.out.println("newnam is "+newname);
}

}
请高手告诉我,错在哪?急!!!!!
class B {public static StringBuffer changStr(StringBuffer str)
{ for(int i=0;i<str.length();i++)
{char B=str.charAt(i);
if(B=='\n') str.setCharAt(i,'n') ;
else if(B=='\b') str.setCharAt(i,'b') ;
else if(B=='\r') str.setCharAt(i,'r') ;
else if(B=='\f') str.setCharAt(i,'f') ;
else ;}
return str; }
static StringBuffer name=new StringBuffer("ni ni hao hao meimei");
static String newname= changStr(name).toString();
public static void main(String[] args){System.out.println("newnam is "+newname);
}

}
不好意思,上次漏了一些东西,这次我把它改好了,编译通过,也能运行,但是得不到预期的结果,我想把字符串的一些空格,退格...用相应的字母表示,请帮我,谢谢了

class B
{
public static String changStr(StringBuffer str)
{
for(int i=0;i<str.length();i++)
{
char a=str.charAt(i);
if(a=='\n') str.setCharAt(i,'n') ;
else if(a=='\b') str.setCharAt(i,'b') ;
else if(a=='\r') str.setCharAt(i,'r') ;
else if(a=='\f') str.setCharAt(i,'f') ;
else ;
}
String str1=new String(str);
return str1;

}

public static void main(String[] args)
{
StringBuffer name=new StringBuffer("n\bni hao hao meimei");
String newname=changStr(name);
System.out.println("newnam is "+newname);
}

}

原题是什么?看不懂这个程序到底要达到什么有用目的,因为好像你想改变的值不会在那name里出现(比如"\r")。

几个表皮错误:
(1) changStr()需要return 一个 StringBuffer 值,但你没有。
(2) 你没有说明 i 是什么。加个 int 在第一个 i 前面。
(3) main() 无法直接运用B里的值,必须要以下方法:
B.changStr(new StringBuffer("ni ni hao hao"));
(4) 最好把String newname这行放在main()里。

(对不起,在下不懂中文程序业的专业词语。)

Could you replace your codes like:
if(B=='\n') str.setCharAt(i,'n')
with the codes like:
if(new Character(B).equals(new Character('\n'))) str.setCharAt(i,'n')
and have a try again with test data "hello world \r\f\b\n hello world"?