 |
|

|
 |

09/03/09 - Variables, Arithmetic Expressions and Loops
|
 |
 |
 |
  | A literal is the actual value of a specific data type. For example, 'A', 'B', '3', and '!' are all literal characters; 234, -5, and 6789 are literal integers; 3.14 and 2.71 are literal doubles; true and false are literal booleans; and "Hello, world!" and "Catch ya later" are literal strings.
|
 |
 |
 |
 |
  | Arithmetic expressions are combinations of numbers with arithmetic operators. Arithmetic expressions evaluate to a numerical value.
|
 |
 |
 |
 |
  | 3 + 4 evaluates to 7. 17 - 3 evaluates to 14. 5 * 8 evaluates to 40. 3*(5+2) evaluates to 21.
|
 |
 |
 |
 |
  | Java has the standard arithmetic operators +, -, *, /. It also has %, the remainder or modulus operator. E.g., 7 % 5 evaluates to 2 because when 7 is divided by 5 the quotient is 1 and there is a remainder of 2. The usual order of operations applies: multiplication and division come first (in order from left to right), then addition and subtraction (in order from left to right).
|
 |
 |
 |
 |
  | Note than an integer divided by an integer results in an integer (any fraction or remainder is discarded).
|
 |
 |
 |
 |
  | A number without a decimal point is assumed to be an int, unless it's too big, and then it's a long.
|
 |
 |
 |
 |
  | A number with a decimal point is assumed to be a double, unless it's followed by a f or F, and then it's a float.
|
 |
 |
 |
 |
  | When an int is added to a double, the int is promoted to a double before the addition, and the result is a double.
|
 |
 |
 |
 |
  | An int can be assigned to a double with no loss in precision.
|
 |
 |
 |
 |
  | However, assigning a double to an int could result in a loss of precision, so a cast is required.
|
 |
 |
 |
 |
  | Variables are declared (memory is allocated for them and a name is associated to them) by typing the name of the data type, then a space, then the name of the variable.
|
 |
 |
 |
 |
  | Variables may also be initialized by assigning them values at the time they are declared.
|
 |
 |
 |
 |
  | Values are assigned to variables by putting the variable on the left side of an = sign and the value to be assigned on the right side.
|
 |
 |
 |
 |
  | An int can be assigned to a double with no loss in precision.
|
 |
 |
 |
 |
  | However, assigning a double to an int could result in a loss of precision, so a cast is required.
|
 |
 |
 |
 |
  | int myInt = (int)3.52; // only the integer part, the 3, is assigned to myInt
|
 |
 |
 |
 |
  | Boolean values and relational operators
|
 |
 |
 |
 |
  | You can compare two values with relational operators: a < b means "a is less than b", a > b means "a is greater than b", a <= b means "a is less than or equal to b", a >= b means "a is greater than or equal to b", a == b means "a equals b", a != b means "a is not equal to b".
|
 |
 |
 |
 |
  | The result of a relational expression is a boolean result: true or false.
|
 |
 |
 |
 |
  | import java.awt.*; import javax.swing.*;
/** DrawingPen is like a drawing pen that * can be moved around a drawing canvas * This is similar to a turtle from the * LOGO programming language. * * @author: David Riley * modified by Chuck Iverson, 2/21/09 */ public class DrawingPen extends JComponent { private static JFrame window; private int locX, locY; private boolean isPenDown; private int direction; private Robot delayTimer; private boolean isHidden; private int windowWidth; private int windowHeight; /** * Sets up drawing window and centers cursor and points it up. * Pen is ready for drawing. */ public DrawingPen() { super(); windowWidth = 700; windowHeight = 700; window = new JFrame( "Drawing Panel"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().setLayout(null); window.setBackground(Color.white); window.setVisible(true); window.setBounds(50, 50, windowWidth + window.getInsets().left + window.getInsets().right, windowHeight + window.getInsets().top + window.getInsets().bottom); locX = windowWidth/2; locY = windowHeight/2; setBounds(locX,locY,9,9); penDown(); direction = -90; window.getContentPane().add(this); repaint(); window.repaint(); try { delayTimer = new Robot(); } catch (Exception e) { System.out.println("This System does not support java.awt.Robot usage."); } }
/** * Pen is centered, pointing up and pen is down. */ public void goHome() { penUp(); locX = windowWidth/2; locY = windowHeight/2; direction = -90; penDown(); } /** * Pen is ready for drawing. * Cursor movement draws line. */ public void penDown() { isPenDown = true; }
/** * Pen is up. * Cursor movement leaves no trace. */ public void penUp() { isPenDown = false; repaint(); }
/** * Cursor is not visible. */ public void hideCursor() { isHidden = true; repaint(); }
/** * Cursor is visible. */ public void showCursor() { isHidden = false; repaint(); } /** * Cursor is rotated right by degrees. * * @param degrees angle to rotate right by */ public void turnRight(int degrees) { direction = direction + degrees; repaint(); }
/** * Position of cursor is changed by specifed distance in the current direction. * * @param distance amount to move in current direction */ public void moveBy(int distance) { Line line; int oldX = locX; int oldY = locY; locX = oldX + (int)(distance * Math.cos(Math.toRadians(direction))); locY = oldY + (int)(distance * Math.sin(Math.toRadians(direction))); setLocation(locX,locY); if ( isPenDown ) { line = new Line(oldX+4, oldY+4, locX+4, locY+4); line.setForeground(getForeground()); window.getContentPane().add(line); line.repaint(); } repaint(); } /** * Window background color is set to newColor. * * @param newColor is the new background color. */ public void setBackground(Color newColor) { window.setBackground(newColor); }
/** * Draws cursor as an arrow at current location * and indicating current direction. */ public void paint(Graphics g) { if (isHidden) return; if (isPenDown) g.setColor(Color.red); else g.setColor(Color.blue); ((Graphics2D)g).rotate(Math.toRadians(direction), getWidth()/2, getHeight()/2); g.drawLine(2, 1, 8, 4); g.drawLine(8, 4, 2, 7); g.drawLine(0, 4, 8, 4); g.drawLine(6, 3, 6, 5); g.drawLine(5, 3, 5, 5); g.drawLine(4, 2, 4, 6); g.drawLine(3, 2, 3, 6); }
/** * Delays cursor movement by specified number of milliseconds. * * @param milliseconds delay amount */ public void delayBy(int milliseconds) { delayTimer.delay(milliseconds); } /** This internal class is used to construct line segments for the drawing tool. */ private class Line extends JComponent { private boolean isMajorDiagonal; public Line(int x1, int y1, int x2, int y2) { super(); setBounds(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2)+1, Math.abs(y1-y2)+1); isMajorDiagonal = (x1==Math.min(x1,x2) && y1==Math.min(y1,y2)) || (x2==Math.min(x1,x2) && y2==Math.min(y1,y2)); } public void paint(Graphics g) { g.setColor(getForeground()); if (isMajorDiagonal) g.drawLine(0, 0, getWidth()-1, getHeight()-1); else g.drawLine(0, getHeight()-1, getWidth()-1, 0); } } }
|
 |
 |
 |
 |
  | Using the DrawingPen class
|
 |
 |
 |
 |
  | 1 - Drawing a square in main using a DrawingPen object
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a square * using a sequence of commands in main. * * @author Chuck Iverson * @version 8/4/09 */ public class Square1 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { // draw the first side pen.moveBy(100); // draw a vertical line 100 pixels long pen.delayBy(500); // wait 500 milliseconds (0.5 seconds) pen.turnRight(90); // turn to the right by 90°
// draw the second side pen.moveBy(100); // draw a vertical line 100 pixels long pen.delayBy(500); // wait 500 milliseconds (0.5 seconds) pen.turnRight(90); // turn to the right by 90°
// draw the third side pen.moveBy(100); // draw a vertical line 100 pixels long pen.delayBy(500); // wait 500 milliseconds (0.5 seconds) pen.turnRight(90); // turn to the right by 90°
// draw the fourth side pen.moveBy(100); // draw a vertical line 100 pixels long pen.delayBy(500); // wait 500 milliseconds (0.5 seconds) pen.turnRight(90); // turn to the right by 90° } }
|
 |
 |
 |
 |
  | 2 - Using a for-loop in main to repeat selected instructions
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a square * using a loop in main. * * @author Chuck Iverson * @version 8/4/09 */ public class Square2 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { for (int i = 1; i <= 4; ++i) { pen.moveBy(100); pen.delayBy(500); pen.turnRight(90); } } }
|
 |
 |
 |
 |
  | Square2 output is the same as Square1 output
|
 |
 |
 |
 |
  | 3 - Moving the for-loop that draws the square into drawSquare(), a separate method, and calling it from main
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a square * using a loop in a separate method. * * @author Chuck Iverson * @version 8/4/09 */ public class Square3 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { drawSquare(); } public static void drawSquare() { for (int i = 1; i <= 4; ++i) { pen.moveBy(100); pen.delayBy(500); pen.turnRight(90); }
} }
|
 |
 |
 |
 |
  | Square3 output is the same as Square1 output
|
 |
 |
 |
 |
  | 4 - Calling the drawSquare() method from a for-loop in main with rotations between calls
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a pattern * in main which uses the drawSquare method. * * @author Chuck Iverson * @version 8/4/09 */ public class Square4 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { for (int i = 1; i <= 24; ++i) { drawSquare(); pen.turnRight(15); } } public static void drawSquare() { for (int i = 1; i <= 4; ++i) { pen.moveBy(100); pen.delayBy(100); pen.turnRight(90); }
} }
|
 |
 |
 |
 |
  | 5 - Passing a parameter to the drawSquare(int side) method to draw squares of variable sizes
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a pattern * in main which uses the drawSquare method with * a parameter to specify the size of the square. * * @author Chuck Iverson * @version 8/4/09 */ public class Square5 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { for (int i = 1; i <= 24; ++i) { drawSquare(200); pen.turnRight(15); } } public static void drawSquare(int side) { for (int i = 1; i <= 4; ++i) { pen.moveBy(side); pen.delayBy(100); pen.turnRight(90); }
} }
|
 |
 |
 |
 |
  | 6 - Drawing rotating squares of decreasing sizes to form a spiral
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a spiral pattern * in main which uses the drawSquare method with * a parameter to specify the size of the square. * * @author Chuck Iverson * @version 8/4/09 */ public class Square6 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { for (int i = 1; i <= 24; ++i) { drawSquare(200-8*i); pen.turnRight(15); } } public static void drawSquare(int side) { for (int i = 1; i <= 4; ++i) { pen.moveBy(side); pen.delayBy(100); pen.turnRight(90); }
} }
|
 |
 |
 |
 |
  | 7 - Drawing smaller, centered squares inside of larger squares
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a nested-square pattern * in main which uses the drawSquare method with * a parameter to specify the size of the square. * * @author Chuck Iverson * @version 8/4/09 */ public class Square7 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { for (int i = 1; i <= 9; ++i) { drawSquare(200-20*i); pen.penUp(); pen.moveBy(10); pen.turnRight(90); pen.moveBy(10); pen.turnRight(270); pen.penDown(); } } public static void drawSquare(int side) { for (int i = 1; i <= 4; ++i) { pen.moveBy(side); pen.delayBy(100); pen.turnRight(90); }
} }
|
 |
 |
 |
 |
  | 8 - Drawing smaller squares inside of larger squares with one corner fixed
|
 |
 |
 |
 |
  | /** * Uses a DrawingPen object to draw a nested-square pattern * with one corner fixed in main which uses the drawSquare method with * a parameter to specify the size of the square. * * @author Chuck Iverson * @version 8/4/09 */ public class Square8 { static DrawingPen pen = new DrawingPen(); public static void main(String [] args) { // pen.hideCursor(); for (int i = 1; i <= 9; ++i) { drawSquare(200-20*i); } } public static void drawSquare(int side) { for (int i = 1; i <= 4; ++i) { pen.moveBy(side); pen.delayBy(100); pen.turnRight(90); }
} }
|
 |
 |
 |
 |
  | 9 - Drawing smaller, centered, rotated squares inside of larger squares
|
 |
 |
 |
 |
  | Challenge: Can you write code to produce the following output?
|
 |
 |
 |
 |
  | Study the code and output of parts 1-8 of Using the DrawingPen class, above.
|
 |
 |
 |
 |
  | Write 8 programs which produce output similar to each of the examples given above, but use equilateral triangles instead of squares.
|
 |
 |
 |
 |
  | Send me your source code and sample output for each of the 8 examples.
|
 |
 |
 |
 |
  | Extra credit: Write a java program which uses the DrawingPen class to create the output in example 9 based on equilateral triangles rather than squares.
|
 |
 |
|


 |
 |
 |