递增计数器一次和两次之间的区别是什么

时间:2017-03-08 17:27:53

标签: java arrays string

我知道编码和练习问题所以我可以变得更好。我在CodingBat上遇到了问题,但我遇到了问题,我不明白为什么我的代码无效。

问题是:给定一个字符串,返回一个字符串,其中对于原始字符中的每个字符,有两个字符。

doubleChar("The") → "TThhee"
doubleChar("AAbb") → "AAAAbbbb"
doubleChar("Hi-There") → "HHii--TThheerree"

我写的代码是

public String doubleChar(String str) {
char[] STR = str.toCharArray();
      char[] two = new char[STR.length*2];
      int counter=0;
      for(int i=0;i<STR.length;i++){
          two[counter]=STR[i];
          two[counter+1]=STR[i];
          counter++;
      }
      String b= new String(two);
      return b;
}

output results //我猜测计数器不能增加counter+1,但仅限于counter++。我能得到更好的解释吗?

在搞乱了一段时间后,我开始工作,但我仍然不明白为什么原来没有。我也是编码的新手,所以我非常感谢你的帮助!

工作:

public String doubleChar(String str) {
char[] STR = str.toCharArray();
      char[] two = new char[STR.length*2];
      int counter=0;
      for(int i=0;i<STR.length;i++){
          two[counter]+=STR[i];
          counter++;
          two[counter]=STR[i];
          counter++;

      }
      String b= new String(two);
      return b;
}

4 个答案:

答案 0 :(得分:1)

在原始解决方案中,只需将计数器变量递增一次。

“counter + 1”不会增加你的计数器值,它只是一个变量和一个数字的加法(计数器+ = 1可以增加计数器变量的值)。

所以,当你这样写:

  two[counter]=STR[i];
  two[counter+1]=STR[i];
  counter++;

这意味着(当counter = 0时)

  two[0]=STR[i];
  two[0+1]=STR[i];
  0++; //So the value of the counter variable is still 0 here

并以适当的解决方案

  two[counter]+=STR[i];
  counter++;
  two[counter]=STR[i];
  counter++;

您将计数器变量递增两次,所以:

  two[0]+=STR[i];
  0++;
  two[1]=STR[i];
  1++;

答案 1 :(得分:0)

功能,

counter++

相同
counter = counter + 1;

在原始代码中,使用值计数器和计数器+ 1,但不更改计数器中的值。您只能在单个计数器++操作中更改它,但必须有2个。或者,您可以写下以下内容:

      two[counter]=STR[i]; //does NOT change the value of counter
      two[counter+1]=STR[i]; //does NOT change the value of counter
      counter += 2; //DOES change the value of counter

答案 2 :(得分:0)

原着:

counter++;

应该是:

counter+=2;

答案 3 :(得分:0)

您需要在原始代码中将counter增加2并且工作正常。在纸上绘制输出:

for(int i=0;i<STR.length;i++){
    two[counter]=STR[i];
    two[counter+1]=STR[i];
    counter++;
}

STR = "The"

i = 0:
   counter = 0;
   two[counter] = two[0] = "T";
   two[counter+1] = two[1] = "T";

i = 1:
   counter = 1;
   two[counter] = two[1] = "h"; (You just overwrote two[1] here, it was "T" but is now "h");
   two[counter+1] = two[2] = "h";

等。

现在有了更正的代码:

for(int i=0;i<STR.length;i++){
    two[counter]=STR[i];
    two[counter+1]=STR[i];
    counter+=2;
}

i = 0:
   counter = 0;
   two[counter] = two[0] = "T";
   two[counter+1] = two[1] = "T";

i = 1:
   counter = 2;
   two[counter] = two[2] = "h";
   two[counter+1] = two[3] = "h";