Chapter 2
<< Chapter 1 | HomeworkTrailIndex | Chapter 3 >>
While Reading and working out "Self-Check" questions, you may wish to have a computer in front of you. Since we are just getting started, it is best to run DrJava in "Interactions Mode" to type the code snippets, or in BlueJ use the "Code Pad". If you can't see the "Code Pad" (it's off by default), go the the "View" menu and select "Show Code Pad." Use the up arrow to scroll back to a previous line so you don't have to start from scratch every time.
Demos--using the Code Pad in BlueJ
- simple data types on the AP Exam: int, double, boolean (not on the Exam: long, float, char)
- Object data type: String (Note the capital--it's a class, so it can have methods)
- the Math class
- the Random class
Another Demo using the Scanner class
import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.print("Type a string:"); String s=in.nextLine(); System.out.println(s.replace('e','3')); } }
Take a look at Roll Your Own
After (or during) your reading of Chapter 2, try these:
Review Exercises
These are important activities to do, but not really something I can grade. This is like the "Training ground" in a video game where you learn the buttons before you go out on a quest. Skip these, and you may not last very long in the game.
WatermellonComponent.java
import java.awt.*; import java.awt.geom.*; import javax.swing.*; public class WatermellonComponent extends JComponent { private Color lightGreen = new Color (0, 255,128); private Color darkGreen = new Color (0, 128, 64); public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; Point2D center = new Point2D.Double(150.0, 150.0); Point2D corner = new Point2D.Double(50.0, 100); Ellipse2D.Double oval = new Ellipse2D.Double(); oval.setFrameFromCenter( center, corner ); g2.setColor(darkGreen); g2.fill(oval); corner = new Point2D.Double(50.0, 110.0); oval.setFrameFromCenter( center, corner ); g2.setColor(lightGreen); g2.fill(oval); corner = new Point2D.Double(50.0, 120.0); oval.setFrameFromCenter( center, corner ); g2.setColor(darkGreen); g2.fill(oval); corner = new Point2D.Double(50.0, 130.0); oval.setFrameFromCenter( center, corner ); g2.setColor(lightGreen); g2.fill(oval); corner = new Point2D.Double(50.0, 140.0); oval.setFrameFromCenter( center, corner ); g2.setColor(darkGreen); g2.fill(oval); } }
WatermellonViewer.java
import javax.swing.JFrame; public class WatermellonViewer { public static void main ( String[] args ) { JFrame frame = new JFrame(); frame.setSize(400,300); frame.setTitle("Watermellon"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); WatermellonComponent w= new WatermellonComponent(); frame.add (w); frame.setVisible(true); } }
RectangleViewer.java
import javax.swing.JFrame; public class RectangleViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 400); frame.setTitle("Two rectangles"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RectangleComponent component = new RectangleComponent(); frame.add(component); frame.setVisible(true); } }
RectangleComponent.java
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JPanel; import javax.swing.JComponent; /** A component that draws two rectangles. */ public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; // Construct a rectangle and draw it Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); // Move rectangle 15 units to the right and 25 units down box.translate(15, 25); // Draw moved rectangle g2.draw(box); // To see the answer to 2.11 box.translate(-15,-25); box.add(0,0); g2.draw(box); } }
- R2.7 Give Java code to construct the following objects:
Create objects, not object variables.
- R2.9 Find the errors in the following statements:
Rectangle r = (5, 10, 15, 20);
double width = Rectangle(5, 10, 15, 20).getWidth();
Rectangle r;
r.translate(15, 25);
r = new Rectangle();
r.translate("far, far away!");
- R2.11 Finding documentation in the API is a vital skill
If you want to see what you are looking for, here is a direct link. It is also printed on page 780. Try finding this page yourself by thumbing through Appendix C, or link to http://www.stfrank.com and select "Java Class Browser". The wiki also has a Java 5 API Link on the sidebar. Once you are in the API, you may wish to make a bookmark in your browser. Now find the "Rectangle" class. Reread section 2.9 if you have trouble.
Make a guess. To see the answer, type these lines in the interactions window of Dr. Java:
import java.awt.Rectangle; Rectangle box= new Rectangle(5,10,20,30); System.out.println(box); box.add(0,0); System.out.println(box);
RectangleClickDemo
The CD has all the source code provided from the author. In addition here is a demo I wrote for you to experiment with. I recommend using BlueJ since this is an Applet. Make a New Project, then Press "New Class". Edit the new Class and delete everything and replace it with the code below. After compliling you can run the applet.
import java.applet.Applet; import java.awt.event.*; import java.awt.*; /** * Class RectangleViewer - write a description of the class here * * @author Fr Chris * @version 22 Aug 2009 */ public class RectangleClickDemo extends Applet implements MouseListener { /** * RectangleViewer is a subclass of Applet * which can draw Graphics and an * implementation of MouseListener * which can collect Mouse clicks from the user * After drawing the box, it will * translate it every time the mouse is * clicked. */ /** * Instance variables */ Rectangle box=new Rectangle(5,10,20,30); /** * init method is executed once * Here we just add the MouseListener * interface to our Applet */ public void init() { addMouseListener(this); } /** * Paint method for applet. * Whenever the screen needs to be * refreshed it will automatically * look for instructions in the paint method * * @param g the Graphics object for this applet */ public void paint(Graphics g) { // simple text displayed on applet g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight() ); g.setColor(Color.black); g.drawString("click to translate box", 120, 120); g.setColor(Color.blue); g.drawRect(box.x,box.y,box.height,box.height); } /** * MOUSE LISTENER IS AN INTERFACE so it requires * that you declare all these methods, * even if you want nothing to happen * * we wish to react to a MouseClick * where we will translate the box */ public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseClicked(MouseEvent e) { box.translate(5,10); repaint(); } }
In class we will add to this so it will count the number of clicks, and maybe even say if you clicked in the box or not.
Programming Exercises
- 2.101 The "elite hackers" like to make their text look cool by replacing characters with similar-looking symbols: e becomes 3, i becomes 1, l becomes 7, and o becomes 0. Complete the following program to carry out these replacements:
public class ReplacementTester { public static void main(String[] args) { String greeting = "Hello, elite hacker!"; // your work here // call the replace method four times System.out.println(modifiedGreeting); System.out.println("Expected: H3770, 371t3 hack3r!"); } }
- 2.102 Complete the following program to compute the average length of the words. Invoke the appropriate method to compute the length of each word, compute the sum of the five results, and divide by 5.0. (Do you know why you need to divide by 5.0 and not simply 5?)
public class AverageTester { public static void main(String[] args) { String word1 = "Mary"; String word2 = "had"; String word3 = "a"; String word4 = "little"; String word5 = "lamb"; // your work here int length1 = . . .; int length2 = . . .; . . . . . . . . . . . . System.out.println(average); System.out.println("Expected: 3.6"); } }
- 2.103 Complete this program by constructing a rectangle with area 51.
// your work here import . . . public class AreaTester { public static void main(String[] args) { // your work here . . . double area = rect.getWidth() * rect.getHeight(); System.out.println(area); System.out.println("Expected: 51"); } }
For 8 points (max), submit you solutions for 2.101-2.103 and show me your working solution to P2.7 (page 76)
//your work here //you need to use the API //see what to import to make an instance of the Random class import . . . /** * DieSimulator answers P2.7. * * @author (your name) * @version (a version number or a date) */ public class DieSimulator { /** * Makes an instance of the Random class called * generator, and uses x=generator.nextInt(6) * x should be a random integer from 1 to 6. * Use the API and look up the Random class. * you may need to do something more to x. */ public static void main (String[] args) { int x; //your work here . . . System.out.println("x = "+x); System.out.println("expected a random number from 1 to 6"); } }
For 9 points (max), submit you solutions for 2.101-2.103 and show me your working solution to P2.8 (page 76) You can start with the starter code for P2.7. You only need one generator... you just need to use it 6 times.
For 10 points (max), submit you solutions for 2.101-2.103 and show me your working solution to P2.10 (page 76) This is tricky, though it doesn't seem tricky.
public class HollePrinter { public static void main (String[] args) { String hi="Hello, World"; //your work here //. . . System.out.println(hi+"\n(Expected \"Holle, Werld\")"); } }
For 11 out of 10 points (max), submit you solutions for 2.101-2.103 and show me your working solutions to P2.10 and P2.15 (page 77) See pp 69-70 in the textbook for hints.
FaceViewer.java
import javax.swing.JFrame; public class FaceViewer { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 400); frame.setTitle("Is It Polite to Make Faces?"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); FaceComponent component = new FaceComponent(); frame.add(component); frame.setVisible(true); } }
FaceComponent.java
import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import javax.swing.JPanel; import javax.swing.JComponent; /** A component that draws an alien face */ public class FaceComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; // Your work here } }