• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

A better way with the if statement?

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! first timer here.

I am working on a school project where I need to draw a wall of bricks with drawRect based on user input. This input asks for how many rows they would like to see. There can be up to 20 rows of bricks. Every odd row needs to be indented a half size. I am OK with the input part. I am currently working on drawing the rows. They way I am doing this works, but there must be an easier way. It is very repetitive.. Here is my code. (numRows is the value they enter). Thanks!

 
Rancher
Posts: 43016
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a number of ways of simplifying this. You could start by getting rid of the duplicated lines of code. If instead of "== 1", "== 2", etc, you wrote ">= 1", ">= 2" etc., what would the code look like?
 
Marshal
Posts: 25594
69
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would refactor those if's like this:

I would likely do more refactoring if I knew what the code was supposed to be doing.
 
David Herron
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WHAT SPEED!

Thank you guys! You just saved me a TON of time. But how does it know to fill in the previous rows? It works, but I am a little confused on why.

Sorry if it should be hitting me in the face.

 
Paul Clapham
Marshal
Posts: 25594
69
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take your pencil and paper and write down which lines of code are executed when (for example) numRows is 3.
 
If you are using a wood chipper, you are doing it wrong. Even on this tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic