User Tools

Site Tools


epgy:ai13:assignment_1

EPGY Assignment 1

Lab 1 - Eclipse


Two disclaimers before you get started on this lab. Disclaimer the first! This lab could be dreadfully boring, mostly new, or somewhere in between. No matter what, don’t dispair! We’ll be moving on to more exciting work soon, but for now we need to make sure everyone is at the same place before we get going. Disclaimer number two! While you might be used to finishing all of your work always, that is not the point of these assignments. Instead, you should finish as much as possible and not stress about anything that you don’t get to. Often times, you will have some time at the beginning of later labs to tie up loose ends. With these words, go to it and have fun!

Introductory Java Materials (Credit: Cameron Alston) - 1 | 2 | 3 | 4 | 5 | 6

Lab 2 - Google Drive


Submission for the class will be all through Google Drive. During our first lab, you should receive an email (ping me if you haven’t) from me with the shared submissions folder. (I'm going to use the e-mail you submitted when you filled out the form for Wordpress).

  1. Find your folder with your .java files. This is your workspace folder if you check the “Copy projects into workspace” checkbox when importing. Otherwise, it is just in the original folder from where you imported the code.
  2. Zip this folder. You can do this by Ctrl-clicking (or right-clicking), and selecting “Compress [your folder name].” A (wild) .zip file will appear.
  3. Make sure that the name of the zip file has your name and the submission title in it.
  4. Drag and drop the file into the appropriate subfolder of the shared submissions folder.
  5. Pray to the Google Drive gods that their product continues to function!
  6. You should have now submitted successfully!

(Taken from: http://aiclassepgy.wordpress.com/2013/06/23/submission-instructions/)

Lab 3 - Review + Graphics Packages


We will do a brief review and get to Graphics Packages when you get a chance.

Review (Credit: Ben Holtz) -

Part 0: Java Warm-up

This is to get everyone on the same page with Java. We assume that you are familiar with a modern programming language coming into the course, so we will run through these exercises with that assumption. (Aka this will be a very fast introduction.) If you are already familiar with Java, run through these anyway. You’ll just get through it nice and quick.

Actual parts where you will have to submit are marked (Deliverable).

  • Start by opening up Eclipse by clicking on the icon on your dock.
  • You should get a prompt for the workspace that looks something like this:

  • The workspace is where all your files, Java resources, and Eclipse settings will be stored. This means that you can just take your workspace folder to any computer, and have Eclipse run identically, settings and everything. You should put your workspace on the fancy EPGY flash drive that you just picked up. This way, you can use a different computer from day to day. Press OK when you’ve chosen your workspace.
  • Now, to download and import a project:
    1. Download this Eclipse project Java Warmup-Starter
    2. (Note: In Eclipse, all your files are organized into “projects.” You can have multiple “projects” open in a workspace, and the code in each is essentially in their own space, unless you choose to connect projects by changing the Build Path options.)
    3. Once Eclipse has started, import them using the import menu option in the file menu. Use the General > Existing projects into workspace option.
  1. Time to start coding!
  2. Java basics
    1. Open up Basics.java
    2. Every Java program has classes. A top-level class like Basics must have the same name as the filename (Basics.java).
    3. Like almost all programming language, Java has functions, or, as we like to call them in object-oriented languages, methods.
    4. The “entry point” of a basic Java program is the method “public static void main(String[] args)”. Don’t worry about what this means just yet. Just know that in a basic, non-graphical program, this is the method that is automatically run when your program runs.
    5. (Deliverable)Let’s try printing some text. Type the following inside the main method.
System.out.println("Woo EPGY!")
  1. Now click the green “play” or “run” button on the toolbar.
  2. You can connect strings and other types by using the concatenation operator, the ‘+’, so you can do stuff like System.out.println(“My name is ” + “Ben”);
  3. Java is an object-oriented language, so almost everything is an Object, but there are a few basic types we call primitives. These are
    1. int — a 4 byte integer object (Of course, for 1, 2, or 8 byte integers we can use byte, short, or long, respectively)
    2. double — an 8 byte decimal (A double precision floating point number, as opposed to the single precision float)
    3. boolean — a boolean value (Either true or false)
    4. char — a single character (If you’ve used other languages like C++, you may be used to using ASCII. However, Java characters are actually Unicode characters. You can still do character arithmetic like myChar-’a’, but just keep in mind that using ASCII will not work.)
  4. In Java, declaration is one step, and initialization and instantiation is a separate step. For example, you can declare an int as “int myInt;” This will declare an integer. For primitive, they all have a default value of either 0, the zero unicode character, or false. However, this is bad programming style. Programming is just as much about making your code clean and easy to read as it is doing something correctly. To explicitly initialize a variable, just use the ‘=’ operator, as in “myInt = 42;” You can do declaration and initialization in one step by doing “int myInt = 1764;”
  5. The basic operators are available– +, -, /, *, and %. The / operator is a truncating division (often called integer division), which means if you divide two integers, it will just round down. The % is the remainder operator (essentially modulo, but technically just a tad different). It will essentially give you the positive remainder after you divide two numbers.
  6. There’re also the shorthands +=, -=, *=, and /=, as well as ++ and — (this is a double-minus–it’s just hard to tell). someNumber += 3 is equivalent to someNumber = someNumber + 3, but just easier to write. someNumber++ is essentially someNumber += 1, with some caveats.
  7. We also have the comparison operators, ==, !=, <, > ⇐, and >=. Notice that to compare equality, you must use double equals. The != means not equals.
  8. (Style) In Java, variable names and method names are, by convention, camelCasedLikeThis. Classes and types are CapitalCamelCasedLikeThis.
  9. (Deliverable) Declare two integers to represent the number of students total this summer in EPGY (guess), and the number of courses (also guess). Find the average number of students per class, and print it out. You can concatenate an int to a String exactly the same way you would concatenate two Strings.
  10. So, speaking of Strings, what are they? Strings are not primitives. They are Objects, with slightly more complexity, and also methods defined on them. In Java, you can call a method on an object by saying myObject.someMethod(). This will call someMethod on myObject. Remember that methods need to be called on an actual instance of an object. So say you have some String, String someString = “this is a string!”;. It would not make sense to do String.length(), since String is the type, it doesn’t make sense to do this. You would call someString.length() to get the length of the string (which should return 17 in this case). Eclipse is super awesome in that it has smart autocompletion, so if you type a dot after a variable, it will automatically list the methods you can call on that object. This is one of the most killer features in Eclipse, and you should totally make use of it.
  11. In Java, Strings are immutable, meaning you can’t change them once you’ve created them. However, you can just create a new string, or reassign the current string. If you are curious about this, ask Ben or one of the RCs.
  12. Also, to compare strings, you must actually use str1.equals(str2) instead of ==. We’ll see why this is the case later.
  13. (Deliverable) Create a few Strings, reassign one of them, and do a print statement with two strings, a double, and a char.
  14. (Deliverable) There’s a method for a String to create a substring. Create a substring of one of your Strings, and print it out.
  15. Some of the things that makes high-level programming languages useful are, of course, control structures. The if statement tests whether a boolean or condition is true, and only executes a statement if it is. The optional else statement will only execute otherwise. Example:
    if (2 < 5) {
       System.out.println("Math works!");
    } else {
       System.out.println("Oh no! Math is broken!");
    }
  16. Something fun to play with is a random number generator. Java makes it very easy to make one. First, let’s create a private static Random object called ‘random’. Do this by typing “private static Random random = new Random();” on a line outside of a method. This, unlike the other variables you’ve created so far, is an instance variable. The other variables are called local variables. Local variables will only exist within the innermost braces they’re in, called the scope, but instance variables will be available and accessible by every method in the class. The “static” means that there should only be one “static” copy of this, accessible by typing ClassName.instanceVariableName, whereas without the static, the variable is attached to each instance of this class, so myClassA.variableName and myClassB.variableName can each have their own copy of variableName.
  17. To use the random number generator after creating it, just call random.nextInt(10); This will generate a random integer between 0 and 9. You can assign this to an int variable of course by saying “int someNumber = random.nextInt(10)”.
  18. (Deliverable) Generate a random number between 50 and 180. (Yes, you will need to use addition (gasp!) for this.) If it is less than 90, print out “Low blood pressure!”. If it is between 90 and 130, inclusive, print out “All normal!”. If it is greater than 130, print out “High blood pressure!”. Watch the edge cases.
  19. By this point, we’ve been using methods without really talking about them in detail. Methods essentially define small segments of code that can be used elsewhere. A method is declared in the file as multiplyStuff. Let’s go through each component of its declaration and implementation:
    1. The private indicates that the method is accessible only within this class. These are often called helper methods since they help this class do its job, but cannot be accessed by other classes. There are three other scopes besides private. If you don’t put down any scoping keyword, Java assumes the package scope, which means that only classes within the same package, or folder, can access the method. A bit more lenient than the package scope is the protected scope. This means that subclasses as well as classes in the package can access this. We’ll talk about what this means a bit later. Finally, you can declare a method to be public, which means that all classes, anywhere, can access this. These same scoping keywords can be used on instance variables.
    2. The static, like the instance variable modifier, just indicates that the method can’t access non-static instance variables. What this means at a high-level is that the method can’t access the instance variables “belonging” to a specific instance of the class, so it can only do stuff based on what you passed in. On the other hand, a method that isn’t static can use instance variables belonging to the specific class. A more specific example of this would be the Java Math class, which dutifully handles operations like exponentiation or trig functions. You certainly could get by without needing a separate instance of Math to give you a sine, so the sine method is given as a static method and called as Math.sine(0.343). This is a tricky concept, so ask for some help if you don’t get it.
    3. The next portion is the return type, or what this method will return back once it completes. In our example, we used an int. If the method doesn’t return anything, the return type will be “void”.
    4. Then comes the methodNameInCamelCase.
    5. Inside the parentheses are the parameters, or what you can pass into the method to make it work. Think of parameters as the inputs to a machine that does some processing, and the return type as the output. In the example method, we pass in three ints as parameters.
    6. In the body of the method, we just multiply the three numbers together.
    7. We then actually return our result using the keyword “return”.
  20. (Deliverable) Create a method called getRandomBetween(int low, int high) that will return a random integer between low and high, both inclusive. In your main method, use this method you just created to print out a random number between -5 and 5.
  21. We can start making this really powerful by doing things repeatedly. In Java, there’s a few ways of doing this, and also a few special loop-related statements:
    1. while loops. While loops are similar to if statements. You have a condition, and you execute what’s in the body if the condition is true. However, you will recheck the condition as soon as you finish the body, and will keep going as long as the condition is true. So, for example, you can have something like the following that will print the numbers 1 to 5.
      int num = 1;
      while (num <= 5) {
          System.out.println(num);
          num++;
      }
    2. for loops. Many times, you have a loop that initializes some variable, will check to see if that variable is in some range, and change that variable in every iteration in the loop. Because this pattern of use happens so often, we have a special loop for it, called the for loop. The previous statement, written as a for loop, would look like the following. Notice how much simpler it is!
      for (int num = 1; num <= 5; num++) {
         System.out.println(num);
      }
    3. break; If you have the statement “break;” anywhere inside a loop structure, you will automatically jump to the first line after then end of the loop. This is useful for getting out of a loop in the middle if some condition was reached.
    4. continue; Sometimes, you want to jump to the end of the loop, but would still like to keep looping. In this case, instead of “break,” use “continue”.
    5. If you return something in a loop, you will also implicitly break out of any loops, since once you return, the method is done.
  22. (Style) Notice that we have been tabbing. The convention is to tab over each time we start a brace. Having correct tabbing not only makes your code more readable and pleasant, but can prevent bugs as well. In Eclipse, if your tabbing starts going awry, you can select all (Apple/Ctrl-A), and auto-tab/auto-indent by hitting Apple/Ctrl-I. .
  23. (Style) You also notice that there are comments in the code. Comments are often crucial to understanding a program, especially for convoluted code. Experienced programmers rigorously comment their code to note how their code works. Many experience programmers also start out a program by just writing comments to plan out their program, and decomposing each commented tasks into methods and subtasks. Such an approach is a combination of two ubiquitous strategies in designing code: pseudocoding anddecomposition. We highly recommend that you do this.
  24. (Deliverable) Create a method called gambleOnZero(int maxNumber). This method will generate generate random numbers between 0 and maxNumber, printing out each as it generates them, and keep generating them until the number 0 is generated, at which time the method ends, return the number of numbers it had to generate to get to 0. In your main method, call the gambleOnZero method, and print out how many times it took.
  25. (Deliverable) Create a method called triangleNumber(int n). The nth triangle number is the total number of items in a pyramid if you have n items at the bottom level, n-1, in the level above that, and so on until you have one item at the very top. Calculate this using a for loop.
  26. (Deliverable) And, to tie it all together, create a method called textTwist(String str, char haltingChar). This method will go through the String str character by charater, and, with 1/3 probability, swap that letter with the next letter in the String. (Obviously, you’ll actually just stop at the second-to-last character in the string.) In addition, we’ll keep doing this either until we reach the end of the string, or reach a character that matches the haltingChar. If that’s the case, we will just return the twisted substring from the start of the string until, and including the haltingChar. Otherwise, we will just return the entire twisted String at the end. Call this with 3 different Strings and print out the results.
  27. Give the people sitting next to you high fives. Honestly, high fives are great, just make sure you give them a heads up.

Part 1: ACMGraphics and Intro

We’ll be using the ACM graphics package developed by the Java Task Force. While many graphics packages are extremely complicated (if you have ever done swing or OpenGL you will understand this feeling) the ACM package is pretty awesome and simple. We should all be able to make awesome GUIs in no time!

Open up GraphicsPractice.java.

You notice that the GraphicsPractice class extends GraphicsProgram. This essentially means that we are going to create a more specific type of GraphicsProgram. We’ll talk more about this tomorrow if the concept is confusing.

You also notice that in the main method, we just start a new GraphicsPractice(). We are essentially creating a new GraphicsPractice program and setting it in motion. When using GraphicsPrograms, you should not put anything else in main.

The two main methods in a GraphicsProgram are init() and run(). Everything you want to happen before the graphics appear should happen in init(). This includes adding buttons, adding text fields, setting the graphics window’s width and height, setting the title, etc. These setup commands should not be done once you finish setup. Hence, you should (almost) never add text fields, buttons, etc in run(). The exact reason for this is a bit complicated, but feel free to ask me if you’re interested. Inside the run(), you can put any code to run once the graphics window appears.

  1. (Deliverable) Put the following line in the init method,
    setTitle("Graphics Practice!");

    and the following two lines outside of any method (these are constants that you are defining):

    public static final int APPLICATION_HEIGHT = 400;
    public static final int APPLICATION_WIDTH = 600;
  2. Hopefully, your program ran, generating an empty 400×600 window with the title “Graphics Practice!” In Java, the window your program opens up is called a frame. The space within the frame where objects can be drawn is called the canvas.
  3. Let’s draw some stuff! The ACM graphics package uses a felt board model, meaning that when you draw an object, you first have to make it, then add it to the canvas. In the run method, add the following lines. Notice that you have to manually set the dimensions, color, location, and fill of the rectangle.
    GRect rect = new GRect(100, 100, 100, 100);
    rect.setColor(Color.RED);
    rect.setFilled(true);
    add(rect);
  4. ACM graphics leaves many more types of shapes at your disposal! Look through the different classes in the API and try drawing one or two others to the canvas.
  5. (Deliverable) Draw your name in the center of the page (using a GLabel), and a personal logo (with any other shapes or classes you’d care to use). For centering, you can use the GLabel’s built in methods, described here.
  6. (Deliverable) Add some color to your logo.
  7. You can clear all the graphics at any point by using removeAll().
  8. Note the use of the new keyword. In Java, new will instantiate (create a concrete instance of) the object you specify. Notice that in object creation, declaration and initialization are very obviously two steps. If you declare GLine myLine, and try to use it without explicitly initializing it, you will get a NullPointerException at runtime, which will make us very, very sad, and most likely crash your program.
  9. Now that you’ve played with drawing, let’s move on to interactors.
  10. (Deliverable) In order to create a button or label, we need to first declare it, then add it. In the init method, add these lines:
    JLabel label = new JLabel("Interactors!");
    JButton button = new JButton("Click me!");
    add(label, SOUTH);
    add(button, WEST);
  11. You will probably get some unhappy red squiggles underneath some of these lines. This is because the JLabel and JButton classes are not imported into the project. If you mouse over the squiggles, a list of options will appear, and from them you can select “import JButton (javax.swing)”. Eclipse is wonderful, isn’t it! You can also use the Organize Imports menu item in the source menu to automatically make these imports.
  12. A label just creates some text along the given edge, in this case, the SOUTH edge.
  13. A button is what you think it is.
  14. Now, to actually do something once we click on the button, we introduce the concept of a listener. Essentially, whenever events happen, like when a button is clicked, when a mouse is clicked, when you press something on your keyboard, etc, the Java “system” will run a method that is “listening” to those events. Let’s wire the button up to a listener and then make the listener respond.
  15. (Deliverable) add a listener to your button in init
    JButton button = new JButton("Click me!");
    button.addActionListener(this);
    add(button, SOUTH);

    add the following method to respond to a click event

    public void actionPerformed(ActionEvent e) {
        System.out.println("Button was pressed!");
    }
  16. Now, whenever the button is pressed, you should get some text being printed out.
  17. So what if you have two buttons? You can check what button was clicked using something like the following:
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Click Me!")) {
            System.out.println("Button was pressed!");
        }
    }

    and something

  18. (Style) Of course, it’s both annoying, and can lead to bugs if you decide to change the text of the button, since you have to change it in two places. A small type can cause bugs. Therefore, it’s always a good idea to use constants instead. In Java, thefinal keyword before a variable declaration means the variable shouldn’t change once it’s created. So, we can do the following, then replace all instances of that string with the constant instead.
    private static final String BUTTON_1_TEXT = “Click Me!”;
  19. (Deliverable) Create two buttons, “Random Circle”, and “Random Rectangle”. Each time one is clicked, draw a random circle or random rectangle. Make sure to use constants.
  20. “A million dollars isn’t cool. Do you know what’s cool? Using the mouse.” Yes, as Justin Timberlake said in “The Social Network,” using the mouse is pretty cool. Every time you click the mouse, move the mouse, drag the mouse, etc, events are being activated all the time. To listen to those events, let’s add the following method. You also need to add the line “addMouseListeners();” to your init method, otherwise the mouse events are not recognized.
    public void mouseClicked(MouseEvent e) {
        System.out.println("x:" + e.getX() + ",y:" + e.getY());
    }
  21. This will run every time a mouse is clicked. The MouseEvent gives some information about where the mouse was clicked and other useful stuff. We can use e.getX() and e.getY() to see where the mouse click was. Run it and click around just to make sure this works.
  22. There are a huge number of types of listeners! Among them, there are keyPressed (a key goes down), keyReleased (key comes back up), keyTyped (a down and back up), mouseDragged (mouse button is down, and is moving), mouseMoved (mouse button is up, and is moving), mouseClicked (a down and up of a mouse button), mousePressed (mouse button goes down), mouseReleased (mouse button goes up), mouseEntered (mouse moves from the outside to the inside of the frame), mouseExited (mouse moves out of the frame), and actionPerformed (buttons, text fields, and other interactors).
  23. (Deliverable) When you click on a spot on the screen draw a small circle around where you clicked.
  24. Give your neighbors another high five!
/soe/sherol/.html/teaching/data/pages/epgy/ai13/assignment_1.txt · Last modified: 2013/07/16 22:15 by ffpaladin