Liz Abbott Liz Abbott - 1 year ago 110
Java Question

how to set up a while loop for

I need to modify this method so that I can enter multiple points for x and y using a while loop. If the value is out of range of 0 - 290 then the loop needs to exit and print "Done". I just learned while loops and I still don't totally understand how they work. This is my code for that method so far.

public void plotPoints(Scanner keyboard)

System.out.print("Enter an x and y coordinate: ");
//Read x from user
int x = keyboard.nextInt();
//Read y from user
int y = keyboard.nextInt();
//Plot the point
new Circle(x,y);

If the user enters an x- or y-value that is out of range (i.e., can't be plotted) the
loop should exit WITHOUT plotting the point. The canvas size is 300x300, so
initially any point less than 0 or greater than 290 (your point diameter is 10)
should cause an exit. (This range will change in the next activity.) Print the word
“Done” after exiting the loop.

If the user enters a x- and y-values that in range, you should plot the point. The
loop will continue and allow the user to enter another point.

Note that, for now, point (0,0) will be in the upper left corner and (290,290) will
be in the lower right
this is currently what I am working on for my lab for my first Cs Class.
I tried using the while loop myself but it ended up printing "done" over and over and it took a minute for the program to stop.

Answer Source

A while loop executes a piece of code until a condition is reached. For example:

int number = 0;

while (number < 5) {

That would print 0, 1, 2, 3 and 4. After that, the condition is false because number == 5.

In your case, you need to use a do while, pseudocode:

do {
    //Ask the user for x, y
} while (x >= 0 && x <= 290 && y >= 0 && y <= 290);


More info about while loop:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download