Draw a hexagon in Java

So I’ve managed to get a for loop that’ll generate a polygon, that turns out just like a hexagon, as I had wished, however, I want to know if you guys can see how I can improve it or how I can simplify it?

        Polygon h = new Polygon();	
	for (int i = 0; i < 6; i++){
		h.addPoint((int) (xPos + side * Math.cos(i * 2 * Math.PI / 6)),
				  (int) (yPos + side * Math.sin(i * 2 * Math.PI / 6)));
	}

Then further down in my code I’ve just got a standard drawPolygon() method passing in my polygon ‘h’, it works just fine, but is there an easier way, also keep in mind that the variable side is based on user input, from a scanner, using the nextInt() method. Side just states the size of it in general, it makes up for both the height and the width, I just thought it would be easier to use the one variable.

Also can you guys think of a nice way no how I could change the colour of the shapes, I was thinking using another loop, something like:

          for (int i = 0; i < 255; i++){
		    r = i;
                    b = i;
                    g = i;
                    color(r g b);
	}

Then some sort of if statement that will check the values of rgb, if they’re now equal to 255, recall the method? - Good idea or bad idea?

You're in Java.... no point in trying to optimize. Just make it easy to read and modify.
If you were in C(C++), I could tell you a handful of optimizations that would speed things up.

Java will never really be efficient. I don't know of any ways off hand that will make things better than what you already have. Seems straightforward enough.

That's a fair enough point, but can you guys thing of a way in which I could make this more readable, or would you say that this is good enough for readability?

I agree, I think that it's pretty straight forward myself, but I thought I'd ask you guys on here, considering some of my fellow class mates are unable to grasp the concept of basic boolean logic. I'm studying a BSc in computer science, some people still don't know how an if statement works, I know I'm only in my first year, but I have no idea how some pupils made it passed the first semester.

I'm first year too.

Our first coursework we had a broken piece of code that had a badly named class and a missing semicolon.

People still managed to not get 100%

1 Like

Waw, I thought that my coursework was easy, the piece of coursework I'm on right now is really easy, we're just working with 9 classes, 90% copy and paste job, all jokes aside, just rename some of the classes/variables and you're pretty much guaranteed to at least get 50-60%.

You shouldnt be aiming for the 60s ;)

I'm actually aiming for the 90's.