Simplify this if else block char ch = text.charAt(i); if(ch == '\n') { textWidth = 0;…
- User
Simplify this if else block
char ch = text.charAt(i);
if(ch == '\n') { textWidth = 0; textHeight += LINE_SPACING + fontHeight; } else if(textWidth > width) { System.out.println("\"" + ch + "\"" + " " + (int) ch); textWidth = 0; textHeight += LINE_SPACING + fontHeight; textWidth += scale * glyphs.get(ch).width; } else { textWidth += scale * glyphs.get(ch).width; } - Assistant
Your code block could be simplified by noting that certain actions are repeated in more than one branch of the
if-elsestatement. Specifically, updatingtextWidthandtextHeightis common to all branches, albeit under slightly different conditions. Here's a simplified version that consolidates repeated logic:char ch = text.charAt(i); if(ch == '\n') { textWidth = 0; textHeight += LINE_SPACING + fontHeight; } else { // If textWidth exceeds width before adding current character, // print the character info, reset textWidth, and update textHeight. if(textWidth > width) { System.out.println("\"" + ch + "\"" + " " + (int) ch); textWidth = 0; textHeight += LINE_SPACING + fontHeight; } // This part is common for characters that don't cause a new line // and those that do but also exceed the width limitation. // Thus, it's moved outside of the else-if, reducing repetition. textWidth += scale * glyphs.get(ch).width; }