user15245113
user15245113

Reputation:

how do alternate between two chars in java

I am doing part of this code where I have to print a square outline. the user enters the length(rows) and width(col) and together with that two char values which should alternate when they print. now I did the swapping trick but it has not worked properly. how can I improve it

here is the code my method caller is

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

    System.out.print(l);

and my method is

   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;
}

my method is printing this

xoxox
o   x
o   x
o   x
oxoxo

but I don't want the o in the same line as we can see there if the first is o then the last should be x. like this

xoxox
o   x
x   o
o   x
oxoxo

how am I supposed to do that tried putting the temporary swap in each for loop but it still gives me the wrong answer. any suggestions please.

and also the rows and columns change according to the user input so it can be 5,5 and noon of the chars should be repeating. a fellow coder helped me improve the code

Upvotes: 1

Views: 191

Answers (1)

Sweeper
Sweeper

Reputation: 271050

Only swap when you are appending a non-whitespace. But note that in the 5x5 case, you don't switch characters when you are in the first column, between the second row and the last row.

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 += " ";
}

I would also recommend using a StringBuilder rather than a appending to a String, to avoid creating a lot of strings:

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();
}

Upvotes: 1

Related Questions