I want to avoiding repeating code. Simplify this if else block char ch = text.charAt(i);…
- User
I want to avoiding repeating code. Simplify this if else block
char ch = text.charAt(i);
if(ch == '\n') { textWidth = 0; textHeight += LINE_SPACING + fontHeight; } else { if(textWidth > width) { textWidth = 0; textHeight += LINE_SPACING + fontHeight; } else { textWidth += scale * glyphs.get(ch).width; } textWidth += scale * glyphs.get(ch).width; System.out.println("\"" + ch + "\"" + " " + (int) ch); } - Assistant
You can simplify the code block by identifying the common actions between the different conditions and structuring the code to minimize redundancy. The key observation here is that updating
textHeightand resettingtextWidthto zero happens in two cases: whenchis a newline character or when . Additionally, updating and printing the character seem to be common actions done for characters that are not newline characters, although there seems to be a mistake in your original code where you update twice. Below is a simplified version: