Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHY281 Scientific Java Programming LoopsSlide 1 Loops In this section we will learn how to repeat a series of instructions using loops and to use this.

Similar presentations


Presentation on theme: "PHY281 Scientific Java Programming LoopsSlide 1 Loops In this section we will learn how to repeat a series of instructions using loops and to use this."— Presentation transcript:

1 PHY281 Scientific Java Programming LoopsSlide 1 Loops In this section we will learn how to repeat a series of instructions using loops and to use this to do animation:  while Loops  for Loops  Infinite Loops  do... while Loops  Exiting Loops  Animation

2 PHY281 Scientific Java Programming LoopsSlide 2 while Loops One of the simplest loops is the while Loop. This keeps looping as long as the test condition is true. while ( ) { } The real power of computers is their ability to do the same or similar things many many times. For this you need loops. Test the condition Body of the loop True False int n = 0; int sum = 0; while (n < 20) { sum = sum + n; n++; } The loop does not necessarily execute at all if the test condition is never met.

3 PHY281 Scientific Java Programming LoopsSlide 3 Parallel Lines import java.awt.*; import java.applet.*; public class Lines extends Applet { public void paint(Graphics g) { int n = 0; int x = 20; int y = 20; while (n < 20) { g.drawLine(x, y, x + 200, y); y = y + 10; n++; } Test counter Increment counter Initialise counter Loop

4 PHY281 Scientific Java Programming LoopsSlide 4 for Loops The most powerful loop is the for Loop. for ( ; ; ) { } Test the condition Body of the loop True False Change Initialise The loop does not necessarily execute at all if the test condition is never met. int sum = 0; for (int n=0; n<20; n++) { sum = sum + n; }

5 PHY281 Scientific Java Programming LoopsSlide 5 A Grid of Lines import java.awt.*; import java.applet.*; public class Grid extends Applet { public void paint(Graphics g) { int x = 20; int y = 20; for (int i=0; i<=10; i++) { g.drawLine(x, y, x + 100, y); y = y + 10; } y = 20; for (int i=0; i<=10; i++) { g.drawLine(x, y, x, y + 100); x = x + 10; } Test counter Increment counter Initialise counter Loop Reset y

6 PHY281 Scientific Java Programming LoopsSlide 6 The scope of the counter for (int i=1; i<=10; i++) { g.drawString("i = " + i, 50, i*10); sum += i; } g.drawString("Sum = " + sum, 50, 120); g.drawString("i = " + i, 50, 130); i is declared in the loop Normally the counter is declared inside the loop - and cannot be used outside (this is known as the scope of a variable). this gives an error as i is undeclared outside the loop int i; for (i=1; i<=10; i++) { g.drawString("i = " + i, 50, i*10); sum += i; } g.drawString("Sum = " + sum, 50, 120); g.drawString("i = " + i, 50, 130); i is declared outside the loop this is now OK (i would be 11)

7 PHY281 Scientific Java Programming LoopsSlide 7 Infinite Loops If you are not careful you can get the program into an infinite loop that go round for ever and are hard to break out of. These all generate infinite loops: for (;;) { g.drawString("looping", 50, 50); } for (int i=1;i<=10;) { g.drawString("looping", 50, 50); } for (int i=1;i>0;i++) { g.drawString("looping", 50,50); } left out the increment test is always true nothing in here

8 PHY281 Scientific Java Programming LoopsSlide 8 Floating Point Counters You may not want the loop counter to increment by integer values. It is perfectly legal to have a floating point loop counter but is usually undesirable. The reason is rounding errors. Because floating point numbers are not stored exactly as you add the increment the number can start to deviate from what you want. It is much better to use an integer loop counter and convert it. public class Floop extends Applet { public void paint(Graphics g) { int x = 20; int y = 20; for (double d=0.0; d<=1.0; d+=0.1) { g.drawString("d = " + d, x, y); y = y + 10; } for (int i=0; i<=10; i++) { double d = i/10.0; g.drawString("i = " + i + " d = " + d, x, y); y = y + 10; } d is not always exactly what you want i is always exactly what you want i is converted into d each time so errors don't accumulate

9 PHY281 Scientific Java Programming LoopsSlide 9 do... while Loops A very similar loop to the while loop is the do... while Loop. The only difference between this and the while Loop is that the conditional test is at the end. do { } while ( ) ; int sum = 0; int i = 1; do { sum += i; i++; } while (i <= 10); Unlike the while Loop the do... while Loop is guaranteed to loop at least once even if the test always fails. Test the condition Body of the loop True False

10 PHY281 Scientific Java Programming LoopsSlide 10 Fibonacci Series public class Fibonacci extends Applet { public void paint(Graphics g) { int x = 10; int y = 20; int iprev = 0; int ilast = 1; int inext = 1; g.drawString(" " + inext, x, y); do { g.drawString(" " + inext, x, y); inext = ilast + iprev; iprev = ilast; ilast = inext; x = x + 40; if (x > 200) { x = 10; y = y + 20; } } while (inext < 1000); } The Fibonacci Series is the series of numbers: 1 1 2 3 5 8 13... where each number (except the first two) is the sum of the previous two numbers. This program prints the Fibonacci series below 1000.

11 PHY281 Scientific Java Programming LoopsSlide 11 Exiting a Loop Normally you exit a loop when the test condition becomes false. However you might like to stop earlier or skip parts of the loop. You can do this using the break and continue statements. break exits the loop immediately. continue stops the current pass through the loop and starts a new one. while ( ) { if ( ) continue; if ( ) break; } goes to the beginning of the loop again goes to the statement after the loop Can be any sort of loop for, while, do... while.

12 PHY281 Scientific Java Programming LoopsSlide 12 Animation By using combinations of loops and decisions we can produce animations i.e. produce a picture that changes with time. One key trick is used in animation to give the impression of movement even though in practice nothing actually moves. If you draw an object and want it to appear to move you delete it and draw it somewhere else. If the computer is fast enough it looks like it moves. For a simple object you can delete it by redrawing it in the background colour. The following program simulates a ball bouncing around inside a rectangle. The movement is simulated by redrawing the ball in the background colour. You can get the current background colour using: Color backgroundColour = getBackground(); which is the opposite of setBackground( ). We move the ball around the screen by incrementing the x and y position. When it gets to an edge we have to change the sign of the incrementaion.

13 PHY281 Scientific Java Programming LoopsSlide 13 Bouncing Ball public class Ball extends Applet { int rectLeft = 50, rectRight = 150; int rectTop = 50, rectBottom = 150; int x = rectLeft + 7; int y = rectTop + 2; int xChange = 2; int yChange = 1; int diameter = 10; public void paint(Graphics g) { continued on next page

14 PHY281 Scientific Java Programming LoopsSlide 14 Bouncing Ball Continued public void paint(Graphics g) { for (int n=1; n < 1000; n++) { g.setColor(Color.black); g.drawRect (rectLeft, rectTop, rectRight - rectLeft, rectBottom - rectTop); Color backgroundColour = getBackground(); g.setColor(backgroundColour); g.fillOval(x, y, diameter, diameter); if (x <= rectLeft) xChange = -xChange; if (x >= rectRight - diameter) xChange = -xChange; if (y <= rectTop) yChange = -yChange; if (y >= rectBottom - diameter) yChange = -yChange; x = x + xChange; y = y + yChange; g.setColor(Color.red); g.fillOval(x, y, diameter, diameter); } Draw new ball Erase previous ball Draw box

15 PHY281 Scientific Java Programming LoopsSlide 15 Slowing it down public void paint(Graphics g) { for (int n=1; n < 1000; n++) { for (int i=1; i<500000; i++) { } g.setColor(Color.black);... If the animation is too fast we can slow it down by introducing a second loop inside the first one (this is called nesting) which does nothing except waste a bit of computer time. This number controls the speed of the ball This number controls how long the animation lasts There are better ways of doing this because here the speed of the ball depends on the speed of your computer.

16 PHY281 Scientific Java Programming LoopsSlide 16 Using sleep import java.util.*;... public void paint(Graphics g) { for (int n=1; n < 1000; n++) { try { Thread.currentThread().sleep(2000); } catch (Exception e){} g.setColor(Color.black);... This number is the time to sleep in milliseconds (2 seconds in this case) If we use the sleep( ) method the program will wait for the time specified before continuing. The time spent sleeping should be independent of the speed of the computer. Unfortunately we have to do some Exception Handling to use it. This means we try to execute what is inside the { } but if it fails for some reason an Exception is thrown. If an Exception is thrown the code inside the { } is executed (which in this case does nothing). Otherwise the program would crash. This just means this bit of the program


Download ppt "PHY281 Scientific Java Programming LoopsSlide 1 Loops In this section we will learn how to repeat a series of instructions using loops and to use this."

Similar presentations


Ads by Google