aspose file tools*
The moose likes Applets and the fly likes A better way with the if statement? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Applets
Bookmark "A better way with the if statement?" Watch "A better way with the if statement?" New topic
Author

A better way with the if statement?

David Herron
Greenhorn

Joined: Jul 27, 2011
Posts: 12
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!

Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42594
    
  65
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?


Ping & DNS - my free Android networking tools app
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18880
    
    8

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

Joined: Jul 27, 2011
Posts: 12
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
Bartender

Joined: Oct 14, 2005
Posts: 18880
    
    8

Take your pencil and paper and write down which lines of code are executed when (for example) numRows is 3.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A better way with the if statement?