//用while语句复制字符串
public class WhileDemo
{
public static void main(String[] args)
{
String copyFromMe="Copy this string until you encounter the etter'g'.";
StringBuffer copyToMe=new StringBuffer();
int i=0;
char c=copyToMe.charAt(i);
while(c!='g')
{
copyToMe.append(c);
c=copyFromMe.charAt(++i);
}
System.out.println (copyToMe);
}
}   请各位看看这段代码,编译运行说是有异常,请教分析一下!! 谢谢

解决方案 »

  1.   


    char c=copyToMe.charAt(i);这句错了吧,应该是char c=copyFromMe.charAt(i);
      

  2.   

    public class WhileDemo
    {
    public static void main(String[] args)
    {
    String copyFromMe="Copy this string until you encounter the etter'g'.";
    StringBuffer copyToMe=new StringBuffer();
    int i=0;
    char c=copyToMe.charAt(i);//NOT copyToMe BUT copyFromMe
    while(c!='g')
    {
    copyToMe.append(c);
    c=copyFromMe.charAt(++i);
    }
    System.out.println (copyToMe);
    }
    }
      

  3.   

    呵呵,碰到string里的g就会终止了。。
      

  4.   

    public class WhileDemo
    {
    public static void main(String[] args)
    {
    String copyFromMe="Copy this string until you encounter the etter'g'.";
    StringBuffer copyToMe=new StringBuffer();
    int i=0;
    char c=copyFromMe.charAt(i);//是读取copyFromMe的一个字符
    while(c!='g')
    {
    copyToMe.append(c);
    c=copyFromMe.charAt(++i);
    }
    System.out.println (copyToMe);
    }
    }
      

  5.   

    public static void main(String[] args) {
    String copyFromMe="Copy this string until you encounter the etter'g'.";
    StringBuffer copyToMe=new StringBuffer();
    int i=0;
    char c=copyFromMe.charAt(i);    //是读取copyFromMe
    while(c!='g')
    {
    copyToMe.append(c);
    c=copyFromMe.charAt(++i);
    }
    System.out.println (copyToMe);
    }犯这种错误!