如何在 java 中的两个字符之间交替

how do alternate between two chars in java

我正在执行这段代码的一部分,其中我必须打印一个方形轮廓。用户输入长度(行)和宽度(列)以及打印时应该交替的两个字符值。现在我做了交换技巧,但它没有正常工作。我该如何改进它

这是代码 我的方法调用者是

String l = TextBox.textBoxString(5,5,'x','o');

    System.out.print(l);

我的方法是

   public static String textBoxString(int rows, int cols, char c1, char c2) {
    String result= "";
    char temp2 = 0;
    for (int i = 0; i <= rows -1; i++){
        for (int j = 0; j <= cols-1; j++){
           
            if(i == 0 || j == 0 || i == rows-1 || j == cols-1){
           temp2 = c2;
           c2 = c1;
           c1 = temp2;
               result += c2 +"";
            }
            else{
                result += " ";
            }
        }
        result += "\n";
    }
    return result;
}

我的方法是打印这个

xoxox
o   x
o   x
o   x
oxoxo

但我不希望 o 出现在我们可以看到的同一行中,如果第一个是 o 那么最后一个应该是 x。 像这样

xoxox
o   x
x   o
o   x
oxoxo

我应该怎么做,尝试将临时交换放在每个 for 循环中,但它仍然给我错误的答案。有什么建议吗

并且行和列也会根据用户输入而变化,因此它可以是 5,5,字符的中午应该是重复的。一位编码员帮助我改进了代码

仅在附加非空格时进行交换。但请注意,在 5x5 的情况下,当您位于第一列时,不会在第二行和最后一行之间切换字符。

if(i == 0 || j == 0 || i == rows-1 || j == cols-1){
    if (i >= rows - 1 || i < 2 || j != 0) {
        // move the swapping code from outside to here
        temp2 = c2;
        c2 = c1;
        c1 = temp2;
    }
    result += c2 +"";
}
else{
    result += " ";
}

我还建议使用 StringBuilder 而不是附加到 String,以避免创建大量字符串:

public static String textBoxString(int rows, int cols, char c1, char c2) {
  StringBuilder result = new StringBuilder();
  char temp2 = 0;
  for (int i = 0; i <= rows -1; i++){
    for (int j = 0; j <= cols-1; j++){
      if(i == 0 || j == 0 || i == rows-1 || j == cols-1){
        if (i >= rows - 1 || i < 2 || j != 0) {
          temp2 = c2;
          c2 = c1;
          c1 = temp2;
        }
        result.append(c2);
      }
      else{
        result.append(' ');
      }
    }
    result.append('\n');
  }
  return result.toString();
}