Week 4-5 Java Programming
Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used when we know exactly how many times we want to loop for While loop Used when we don’t exactly know how many times we want to loop for
Loops For loop structure: for(int i = 0; i < #; i++) { code here; } Programmers conventionally start counting at zero (zero- based numbering) Replace the # with the number of times you want the code looped
Loops For loop: Let’s create a program that will print 1 through 100 using a for loop that loops 100 times for(int i = 0; i < 100; i++) { System.out.println(i + 1); }
Loops While loop structure: while(boolean someBool) { code here; } Notice that the boolean someBool will need to be true in order for it to enter the while loop (it acts as an if/else staement), inside the code is where you want to make it so that someBool will eventually become false in order for it to exit the loop or else it will loop infinitely and crash.
Loops While loop: In a while loop, there is a condition, the condition is a comparison between two values in which if turned false it will exit the loop, else it will loop until your computer runs out of memory (crash) Example: int age = 0; while(age < 20) {// (age < 20) is the condition System.out.println(age); age++;// age is increased by 1 with every }// loop
Loop Example: Count to from 1 to 100. Would it be better if we used for loop or while loop in this case? Given a list of 100 numbers from 1 to 100, randomly placed. I want you to find where the number 40 is located starting from the beginning of the list. Would it be better if we used for loop or while loop in this case?
Learning to count like a programmer Most programmers count starting from zero Be extra careful when counting in programming, when I ask for position 5, what it really means is 6 units from the left since 0,1,2,3,4,5 is 6 units. When using String functions such as stringName.substring(0,5) will get the letters from the 0 th position to the 4 th position because the last letter is EXCLUDED (its how this function is programmed) Example: String someString = “Hello”; someString.substring(0,3) will return “Hel”
Object Oriented Programming OOP is a program model which is based on objects instead of actions. Objects contain methods and values, methods are the procedures and values are the data for the program. An object is an instance of a class and it only defines data it needs to be concerned with, the code will not be able to accidently access other program data. The idea of a class is that it is reusable not only by the program that it was initially intended for but also other object oriented programs. The concept of data class allows the user to create a new objects that haven’t already been defined in the language itself
Creating an OOP Program Create an object and then use it in the main function WaterBottle.java WaterBottleMain.java WaterBottle.java contains the object’s details and what we can do with the object WaterBottleMain.java is just a regular program (the one with the main header function) that we will use to implement the object WaterBottle
Creating an OOP Program WaterBottle.java and WbMain.java
Creating an OOP Program What is contained in an Object file? Constructor – Default values for the object once it’s created and stored into memory for later use Accessor Methods are used to retrieve data about the object Keyword for Accessor Methods is “get” Mutator Methods are used to set data about the object Keyword for Mutator Methods is “set”
Randomization There is no true random generator that exists in computer programming, only complex patterns. Eventually numbers will repeat itself. If you think about it, you can throw dice and the number that appears on top will be random. But in computer terms, the programmer must tell exactly how the dice will select the number, through a complex algorithm. Algorithm - A process or set of rules to be followed in calculations or other problem-solving operations, esp. by a computer.
Randomization There is a complex algorithm implemented in Java’s library, we’re going to be using this algorithm to obtain randomly generated numbers Since it’s in the library, we’ll have to take it out of the library and into our code by using this command: import java.util.Random;
Randomization Using the random command, we’ll have to declare it like we do to data types like integers etc. We declare a random object by: Random myVar = new Random(); Now myVar is of type Random, we’ll be using myVar to generate our random results
Randomization How to use it: You can use it in various ways, we can store the random number that is generated into memory (by creating an integer variable and setting it to the random number) or simply just printing it Random myVar = new Random(); int myInt = 0; myInt = myVar.nextInt(100); This code will generate random numbers from 0-99 and store it into the variable myInt
Dice Create Dice.java and DiceMain.java
Arrays What are arrays? You can think of an array as a list This “list” can only contain one data type Before creating an array, you have to already know how much space your list should reserve Arrays are static which means it cannot be changed Once an array of a certain size is set, the size can’t be changed which is why you must know exactly how much space you need before using an array
Arrays How do we use arrays? Arrays are defined in Java by default, so all we have to do is declare it, we declare it by: int[] myVar = new int[5];// This reserves space for 5 integers Notice that we’ve added square brackets, this is how an array is declared, the new int[5]; means we’re creating room for 5 integers
Arrays How we would use arrays: int[] myVar = new int[5]; myVar[0] = 1; myVar[2] = 3; myVar[1] = 10; myVar[3] = 6; myVar[4] = 600; Notice that we use the variable name followed by square brackets with a number inside, the number inside is the address number, it locates the space on the list and then assigns a value to the space Also notice that the number does not have to be in order, you can assign a value to the space however you like
Arrays Instead of using: int[] myVar = new int[5]; We can use this if we already know the integers we want stored on the list int[] myVar = {10, 3, 1, 6, 600, 500, 200};
Arrays You don’t always have to use integers for arrays, I just used it for an example, you can store other data types like Strings etc. String[] myVar = new String[10]; myVar[0] = “This is the first string”;
ArrayLists What are ArrayLists? Similar to Arrays, ArrayLists is a list that holds a specific data type (or different ones using when you define the ArrayList as an “Object) ArrayLists are unlike the Array in the sense of space, ArrayLists are Dynamic meaning that you can adjust the size once you create the ArrayList *Remember that in Arrays, you cannot adjust the size once the Array is declared; which is why it’s Static
ArrayLists Before using an ArrayList, you must import it from the library import java.util.ArrayList; Declaring an ArrayList ArrayList myVar = new ArrayList ();
ArrayLists ArrayList Functions: ArrayList myVar = new ArrayList (); myVar.add(“Amy”);// Adds the string Amy to the list myVar.add(“Bruce”);// Adds the string Bruce to the list myVar.get(0);// Retrieves the information at index 0 myVar.get(1);// Retrieves the information at index 1 myVar.remove(1);// Removes the object at index 1 myVar.get(0).equals(“Amy”); // True myVar.isEmpty();// True if empty, false if not myVar.size();// Returns the size of the list
ArrayLists Example import java.util.ArrayList; public class arrayListMain { public static void main(String[] args) { ArrayList myArrayList = new ArrayList (); myArrayList.add(1);// Value 1 is stored at Position 0 myArrayList.add(5);// Value 5 is stored at Position 1 myArrayList.add(6);// Value 6 is stored at Position 2 System.out.println(myArrayList.get(1)); }
Program 2 Program 2 (Follow along) Deck.java, Cards.java, DeckMain.java
Graphical User Interface (GUI) What is a GUI? Graphical User Interface is the visual portion of the program From the beginning up until now we’ve been programming the behind the scenes portion of the program or we can say the machine under a car’s hood Now we can create a program that has the actual outer layer, for example the chassis of the car GUI consists of windows, buttons, menus etc.
GUI Types of GUI There are many types of GUI, we’ll be using two JOptionPane Used for forms which usually requires user’s input (Like forms etc.) JFrame Simple window that allows your contents to be placed on
GUI - JOptionPane Before using JOptionPane, you must import it from the library import java.swing.JOptionPane; Swing is a GUI widget toolkit for Java Contains files needed to create GUI’s
GUI - JOptionPane Use JOptionPane to create a form querying user name and age GUI.java
GUI - JFrame JFrame Jframe is a basic window where you can put your contents on Because of Jframe’s complexity, we’ll be using a program called NetBeans to handle our GUI processing This will make your life much much easier This program is a GUI for you to create your own GUI program, it’s a click and drag type of program With NetBeans, you don’t have to worry about the placement of your labels/buttons etc. all you have to worry about is the mechanics behind your program (How it operates)
GUI - JFrame Before using JFrame, you must import it from the library import java.swing.JFrame; Swing is a GUI widget toolkit for Java Contains files needed to create GUI’s