Hi, i have the following code in Java as you can see there are a lot of code repetition. I want to know how i can loop this part of code instead of writing it each time?

g.setColor( Color.black );
      g.fillArc( 110, 80, 300, 300, 0, valint[0] );
      
      
      g.drawString("BMW", 420, 80);
      Rectangle2D BMW = new Rectangle2D.Double(400, 70, 10, 10);
      gd.draw(BMW) ; gd.fill(BMW) ; 

      g.setColor( Color.red );
      g.fillArc( 110, 80, 300, 300, valint[0], valint[1] );
      
      
      g.drawString("Mercedes", 420, 100);
      Rectangle2D mercedes = new Rectangle2D.Double(400, 90, 10, 10);
      gd.draw(mercedes) ; gd.fill(mercedes) ; 

      g.setColor( Color.blue );
      g.fillArc( 110, 80, 300, 300, valint[0]+valint[1], valint[2] );
      
      
      g.drawString("Honda: 120", 420, 120);
      Rectangle2D honda = new Rectangle2D.Double(400, 110, 10, 10);
      gd.draw(honda) ; gd.fill(honda) ; 

      g.setColor( Color.green );
      g.fillArc( 110, 80, 300, 300, valint[0]+valint[1]+valint[2], valint[3] );
      
      
      g.drawString("Toyota: 130", 420, 140);
      Rectangle2D toyota = new Rectangle2D.Double(400, 130, 10, 10);
      gd.draw(toyota) ; gd.fill(toyota) ; 


      g.setColor( Color.white );
      g.fillArc( 110, 80, 300, 300, valint[0]+valint[1]+valint[2]+valint[3], valint[4] );
      
      
      g.drawString("Nissan: 150", 420, 160);
      Rectangle2D nissan = new Rectangle2D.Double(400, 150, 10, 10);
      gd.draw(nissan) ; gd.fill(nissan) ;

Edited 4 Years Ago by MozammilK: n/a

you're not looking for a 'loop', you're looking for reusability of code.
write the repeating code in a method, and the variables, the parts that differ, that are the arguments you pass as parameters each time you call the method.

you're not looking for a 'loop', you're looking for reusability of code.
write the repeating code in a method, and the variables, the parts that differ, that are the arguments you pass as parameters each time you call the method.

Fair. I get what you mean. This code is drawing a pie chart and i wanted to do it with a single statement, in a loop.

For e.g

for (int i=0; i<value.length ; i++) {g.fillArc( 110, 80, 300, 300, valint[i], valint[i+1] )}

Edited 4 Years Ago by MozammilK: n/a

you'll want to loop over a bit more than just that.

g.setColor( Color.white );
g.fillArc( 110, 80, 300, 300, valint[0]+valint[1]+valint[2]+valint[3], valint[4] );
 
g.drawString("Nissan: 150", 420, 160);
Rectangle2D nissan = new Rectangle2D.Double(400, 150, 10, 10);
gd.draw(nissan) ; gd.fill(nissan) ;

if you look above, that is the code you are repeating.
put all that in a method, where you pass the variables that change every time (the color, for instance) as parameters. let's say, you call that method
createPart(params)

than you just loop a bit like this:

for (int i=0; i<value.length ; i++) { createPart(params);}
This article has been dead for over six months. Start a new discussion instead.