Different character outputs using loops and strings

I’ve just given this as a response to an absolute beginner on SO, and I’m wondering how terrible it is.

Output for an odd number of lines:

>
>>>
>>>>>
>>>
>

Output for an even number of lines:

>
>>>
>>>>>
>>>>>
>>>
> 

The code:

int lines = 7;
int half = lines/2;
String carat = ">";
int i;

//better to declare first or does it not matter?         

if(lines%2==0){boolean even = true;}
else{boolean even = false;}

for(i=1;i<=lines;i++){
        System.out.println(carat + "\n");
        if(i==half && even){System.out.println(carat+"\n");}
        if(((i>=half && even) || (i>=half+1)) && i!=lines){
                carat = carat.substring(0,carat.length()-2);
        }else{
                carat = carat + ">>";
        }
}

This code just seems so ugly, not considering the fact that there is no method that takes number of lines and that it is abusing integer rounding.

Answer

better to declare first or does it not matter?

No. These days most people believe variables should be declared as late as possible, right by where they are used.

This code just seems so ugly.

It is. A little whitespace in there would help a lot. Which is easier to read:

// This:
if(i==half && even){System.out.println(carat+"\n");}

// Or this:
if (i == half && even) {
  System.out.println(carat+"\n");
}

that it is abusing integer rounding.

There’s no abuse, and it’s not rounding. Truncation on integer arithmetic is a specified part of the language. Feel free to use it. In this case, it does exactly what you want.

If I were writing this, I’d do:

printCarats(int numLines) {    
  for (int line = 0; line < numLines; line++) {
    // Mirror vertically across center line.
    int halfLine = line;
    if (line > numLines / 2) halfLine = numLines - line - 1;

    int numCarats = 1 + halfLine * 2;
    for (int i = 0; i < numCarats; i++) {
      System.out.print(">");
    }
    System.out.println();
  }
}

Attribution
Source : Link , Question Author : Brandon Frohbieter , Answer Author : Jörg W Mittag

Leave a Comment