ATM Machine Simulator in Java Code

User Generated

zlnaxrrf

Programming

Description

Bank of America has decided to replace their old, COBOL programmed, ATM machines. ACME Machines, your employer, has won the contract to create and deliver the 500 new ATM machines that Bank of America is going to need. At the lead programmer for ACME Machines, it is going to be your responsibility to create the software that the new ATM machine will use.

Bank of America has provided an overview of how their customers typically interact with an ATM machine. The bank customer enters their card into the machine and then types in their PIN. Bank security then verifies the card. The user selects the account to use (e.g. checking or savings). They then select an amount to withdrawal. Security verifies if the amount is available. The system then makes a decision as to if it is going to provide the money. The ATM provides the funds if possible. The ATM provides a receipt and returns the card to the user.

The Java program that you will create to control this ATM machine will start with a main method; however, then control will be transferred to a series of classes. Your program will contain at least the following classes and methods:

  • Class: ATMCard o (1) Variable: cardNum – holds a single ATM card's ID number o (1) Variable: cardPIN – holds a single ATM card's PIN number o (1) Variable: checking balance – amount of money in this person's checking account o (1) Variable: savings balance – amount of money in this person's savings account
  • Class: CardServices o (2) Method: initializeCardDB – creates an array containing ATM card numbers and PINs o (3) Method: insertCard – checks to see if the inserted card's ID number is recognized o (6) Method: processCard – allows a user to request funds to withdraw o (12) Method: returnCard -returns the inserted card to the user
  • Class: PINo (4) Method: processPIN – compares the entered PIN to the PIN stored for this card o (5) Method: eatCard – if the PIN is incorrectly entered four times, this eats the card
  • Class: Securityo (9) Method: verityBalance – ensure that the card owner's account has enough money o (10) Method: verifyMachineBalance-- ensure that the ATM machine has enough money
  • Class: Account o (7) Method: select – determines if the user wants to withdraw from checking or savings
  • Class: Money o (8) Method: enterAmount – asks user to enter the amount that they want to withdraw
  • Class: Dispense o (11) Method: ones – dispenses ones o (11) Method fives – dispenses fives o (11) Method: tens – dispenses tens o (11) Method: twenty's – dispenses twenty's

o

You can assume that the ATM has been loaded with $1,000 in the following denominations:25 $20 bills, 25 $10 bills, 40 $5 bills, and 50 $1 bills. The ATM machine will attempt to provide every customer with money using the largest available bills assumingthat the machine still has enough money to fulfill the request – denominations don't matter (i.e. it could use all $1 if that's all that it had left)

The ATM machine should be programmed to display "Wrong PIN", "Unrecognized card", and "Out of money – cannot complete transaction". The machine should "eat" the ATM card if the PIN is entered incorrectly 4 times.

The machine will be preloaded to recognize the following ATM cards:

Card Number

PIN

Checking

Savings

123456789

1111

$550

$1,275

135792468

2097

$90

-1

019283746

6194

$715

-1

675849302

0071

$790

$211

347821904

9871

$113

$78

Note that "-1" means that an account does not exist.

Once you've created your ATM machine, simulate the following transactions:

  • John Smith has both a checking and a savings account with BoA. He uses the ATM with card 123456789 and enters PIN 1111. He then requests $250 from his checking account.
  • Amy Rain has accounts at Citi Bank. When he inserts his ATM card into the BoA ATM machine with card ID number 347821905 the ATM machine should reject it.
  • Paul Logan has both a checking and a savings account with BoA. He uses the ATM with card 675849302 and enters PIN 0071. He then requests $500 from his checking account.
  • Tammy Placard only has a checking account. She then uses the ATM with card 135792468, but can't remember her PIN. She tries 2000, 2090, 2077, and 2079.
  • Jill Holland only has a checking account with BoA. She uses the ATM with card 019283746 and enters PIN 6194. She then requests $300 from her checking account. This amount is refused because the machine does not have that much money. She then requests $250 and the machine completes the transaction.

Note: You are only permitted to use the Java commands that we have covered in class so far. Yes, there are many more, but no, you can't use them in solving this homework!

Homework Assignment: Submit an electronic copy of your program via the Canvas tool.

Assignment Requirements:

  • You are required to submit an electronic copy of your program online via the Canvas tool.
  • Javadoc comments should be included for each class, method, and parameter. Before each method, put the following comment lines:
    • Method Name: xxx
    • Description: xxx
    • @param xxx
  • Your code must contain the following comment header:

/**

*

*/

//

// COP 2510 – Spring Semester, 2020

//

// Homework #1: The New ACME Machines ATM Machine

//

// (Your Name)

//

Unformatted Attachment Preview

An Introduction To Solving Problems Using Java & Design Patterns Lecture #2: Breaking The Surface How To Get In Touch With The TAs • Ashik Barua ashikbarua@mail.usf.edu EMB 216 MW 3:00pm – 5:00pm TR 11:00pm - 2:00pm Set up an appointment!!! • Qi Zheng qizheng@mail.usf.edu ENB 216 MW 12:30pm - 2:30pm 2 Image Credit: https://www.dckids.com/teen-titans-go/robin What Is Java Made Up Of? Variables math strings I/O IF/Else Switch While For Arrays And/Or/Not MethodsCasts Classes Enumerated Break 3 Different Tools For Different Jobs: Why Use Java? Why Use Java? • Need to run your program on any platform: computers, laptops, gaming consoles, Blu-ray players, car navigation systems, medical monitoring devices, parking meters, lottery terminals and smartphones. • Need to run a program in a browser: miniature, dynamic programs that run alongside or are embedded within Web pages. • It is hard to write Java programs that crash: it is memory safe. You cannot have dangling pointers, buffer overflows, and for the most part it eliminates memory leaks. • Java programs come with security built-in: Java provides one with the most secure environment. Even though it is running on a network, one can be sure about the online security with java run-time environment. • Great collection of Open Source Libraries • Wonderful Community Support Image Credit: https://www.123rf.com/photo_22009371_a-businessman-have-a-good-idea.html Example: Sony UBP-X700 Ultra HD Blu-ray Player • Power on, Power off, Eject • Setup screen: WiFi, Color, Sound • Select track to play • Pause, Stop, Fast Forward, Rewind • Facts of Life: – Next version’s user interface should have same look / feel, – May use a different processor, – Will have additional features Different Versions Of Java • There are three different versions of Java – each designed for a different purpose – Java SE (“Standard Edition”) - This is the core Java programming platform. It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...). – Java EE (“Enterprise Edition”) - if your application demands a very large scale, distributed system, then you should consider using Java EE. Built on top of Java SE, it provides libraries for database access (JDBC, JPA), remote method invocation (RMI), messaging (JMS), web services, XML processing, and defines standard APIs for Enterprise JavaBeans, servlets, portlets, Java Server Pages, etc. – Java ME (“Micro Edition”) - This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes. Java ME provides a subset of the functionality of Java SE, but also introduces libraries specific to mobile devices. Because Java ME is based on an earlier version of Java SE, some of the new language features introduced in Java 1.5 (e.g. generics) are not available. Image Credit: www.codingeek.com What Is The Java SDK (JDK)? • The Java Development Kit (JDK) is an implementation of either one of the Java SE, Java EE or Java ME platforms released by Oracle Corporation in the form of a binary product aimed at Java developers on Solaris, Linux, Mac OS X or Windows. • The JDK also comes with a complete Java Runtime Environment, usually called a private runtime, due to the fact that it is separated from the "regular" JRE and has extra contents. It consists of a Java Virtual Machine and all of the class libraries present in the production environment, as well as additional libraries only useful to developers, such as the internationalization libraries and the IDL libraries. • The JDK includes a private JVM and a few other resources to finish the development of a Java Application. Image Credit: javacompile.blogspot.com Software That You’ll Need For This Class • Java SE 13.0.1 – The “Java Development Kit” – The Java Development Kit (JDK) is an implementation of the Java Platform, Standard Edition released by Oracle Corporation in the form of a binary product aimed at Java developers on macOS or Windows. – https://www.oracle.com/technetwork/java/javase/downloads/index.html • Eclipse – An Integrated Development Environment (IDE) – Very popular in the real world – https://www.eclipse.org/eclipseide/ How Does This Java Thing Work? The goal of Java is to write one application and have it work on whatever device your users have. Example: Creating A Graduation Party Invitation A History Of Java 1995 1997 1999 2004 Version Names: Version 1.2 was such a big change, Sun marketing decided to call it Java 2. Same thing for version 1.5 – marketing decided to call it Java 5 Sample Java Code Code Structure In Java Source File Class File What is a source file? A source code file has a “.java” extension public class Dog { and contains one class definition. This class represents a piece of your } program. The class must go between a pair of curly brackets. Method 1 statement What goes into a class? A class will have one or more methods. Methods must be declared inside of a class. public class Dog { void bark() { } } What goes into a method? Method code is a set of statements. Think of a method as being like a function. public class Dog { void bark() { statement1; statement2; } } Method 2 statement statement statement How Does The JVM Process Java Code? • When the JVM starts running, it looks for the class that it was given at the command line. • Then it starts looking for a specially-written method that looks like: public static void main (String[] args) { // insert your code here } • The JVM then runs all of the code between the {} of the main method. • Every Java application has to have at least one class, and at least one main method. • Note: not one main method per class, just one main method per application. Image Credit: jcrunchify.com How To Write A Class With A Main • In the Java language, everything goes into a class. You type your source code into a file that has the .java extension. This gets compiled into a file that has the .class extension. When you run your program, you are really running a class… • When you run a program, what you are really doing is telling the Java Virtual Machine (JVM) “… load my class and then start to execute its main() method. Continue running until all of the code in the main method has been executed…” • The main() method is where your code always starts to run. • No matter how many classes your program contains, there will always has to be a main() method in order to get things started. Image Credit: www.how-to-write-a-book-now.com Running Java Code 1 What Can You Say In The Main Method? • Do Something – Declarations, assignments, method calls, etc. • Do Something Over And Over – For and While loops • Do Something Under This Condition – If / Then / Else tests Image Credit: www.ilovemuslims.net Java Syntax Rules • Each statement must end with a semicolon: z = z + 1; • A single-line comment begins with two forward slashes: // this is a comment • Most white space does not matter. • Variables are declared with a name and a type. int weight; // type: int, name weight • Classes and methods are defined within a pair of curly braces public void go() { // insert code here } Image Credit: www.zazzle.com Looping • Java has three standard ways of doing loops: for, while, and do-while • Let’s look at while: the key to a while loop is its conditional test. A conditional test is an expression that results in a Boolean value – something that is either true or false. • Simple Boolean tests: – < (less than) – > (greater than) – == (equal) Image Credit: www.pbase.com Sample Looping Code int x = 4; // assign 4 to x while (x > 3) { // loop code will run because // x is greater than 3 x = x - 1; // or we’d loop forever } int z = 27; while (z == 17) { // loop code will not run because // z is not equal to 17 } Image Credit: www.enthusiasticencounters.com Sample While Loop Project public class Loopy { public static void main (String[] args) { int x = 1; System.out.println(“Before the Loop”); while (x < 4) { System.out.println(“In the loop”); System.out.println(“Value of x is ” + x); x = x + 1; } System.out.println(“This is after the loop”); } } 2 Image Credit: all-free-download.com Common Questions • Do I have to put a main() into every class that I write? Answer: No. A Java program may use many different classes, but you only need one main() method. This will be the one that starts the program running. • In C++ you can do a Boolean test on an integer: x = 1; while (x) {do something}. Does Java support this? Answer: No. In Java, a Boolean and an Integer are not compatible types. The result of a conditional test must be a Boolean so the only type of variable you can directly test must be a Boolean variable. Image Credit: www.jobinterviewtools.com Quick Review • Statements end in a semicolon ; • Code blocks are defined by a pair of curly braces { } • Declare an int variable with a name and a type: int x; • The assignment operator is one equals sign = • The equals operator uses two equals signs == • A while loop runs everything within its block (defined by curly braces) as long as the conditional test is true. • If the conditional test is false, the while loop code block won’t run, and execution will move down to the code immediately after the loop block. • Put a boolean test inside parentheses: while (x == 4) { } Image Credit: www.snoringmouthpieceguide.com Conditional Branching • In Java, an IF test is pretty much the same as the Boolean test in a WHILE loop. class IfTest { public static void main (String[] args) { int x = 3; if (x == 3) { System.out.println(“x must be 3”); } System.out.println(“This runs no matter what”); } } Image Credit: martianchronicles.wordpress.com Else class IfTest2 { public static void main (String[] args) { int x = 2; if (x == 3) { System.out.println(“x must be 3”); } else { System.out.println(“x is NOT 3”); } System.out.println(“This runs no matter what”); } } Image Credit: www.transart.org Printing Output • System.out.print vs. System.out.println – System.out.println inserts a new line character at the end of what you print – System.out.print does not insert a new line character and so you’ll keep printing to the same line. Image Credit: picoprinting.com In-Class Programming Challenge • Create a program to print out the words to the “99 bottles of beer on the wall” song. • Sample output: 73 bottles of beer on the wall 73 bottles of beer on the wall 73 bottles of beer. Take one down. Pass it around. 72 bottles of beer on the wall 72 bottles of beer on the wall 72 bottles of beer. Take one down. Pass it around. • Start at 99, end at 0 bottles of beer. Image Credit: www.londonpowertunnels.co.uk A Solution To Beer Song Challenge package beersong; public class BeerSong { public static void main(String[] args) { int beerNum = 99; String word = "bottles"; while (beerNum > 0) { if (beerNum == 1) { word = "bottle"; // singular, as in ONE bottle. } System.out.println(beerNum + " " + word + " of beer on the wall"); System.out.println(beerNum + " " + word + " of beer."); System.out.println("Take one down."); System.out.println("Pass it around."); beerNum = beerNum - 1; if (beerNum > 0) { System.out.println(beerNum + " " + word + " of beer on the wall"); } else { System.out.println("No more bottles of beer on the wall"); } // end else } // end while loop } } Image Credit: www.huffingtonpost.com What We Covered Today 1. 3 types of Java 2. What is the Java SDK 3. Code structure in Java 4. Anatomy of a class 5. The main() method 6. Looping / Conditional branching (if tests) Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Inheritance (an introduction) 2. Overriding methods (an introduction) 3. What’s in a class? (methods, instance variables) Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java & Design Patterns Lecture #3: A Trip to Objectville A Class Is Not An Object • However, it is used to construct them • A class is a blueprint for an object. It tells the JVM how to make an object of that particular type. Each object made from that class can have its own unique variable values. Image Credit: www.chickslovethecar.com How To Create An Object In Java • To create an object, you need to create two classes. • One class will be for the type of object you want to create (person, spacecraft, button, etc.) and the other will be used to test the operation of your object class. • In the tester class, we’ll put the main() method and in the main() method we’ll test creating and accessing objects of our newly created type. Image Credit: thesolidphp.com Java Object Creation Example: Movie Objects Class Variables Method Java Object Creation Example: Movie Objects class Movie { String title; String genre; int rating; void playIt() { System.out.println(“Playing the movie”); } } 1 public class MovieTestDrive { public static void main(String[] args) { Movie one = new Movie(); one.title = “Gone with the Stock”; one.genre = “Tragic”; one.rating = -2; Movie two = new Movie(); two.title = “Lost in Cubicle Space”; two.genre = “Comedy”; two.rating = 5; two.playIt(); Movie three = new Movie(); three.title = “Byte Club”; three.genre = “Tragic but ultimately uplifting”; three.rating = 127; } } Image Credit: movie.idevcreations.com The Two Purposes Of Using The Main() Method 1. To test your real class 2. To launch/start your Java application Image Credit: www.123rf.com Java: Objects Talking To Objects • In Java, most of what goes on is that objects call methods that are part of other objects. • In our past examples, the main() method from TestDrive created and tested methods in other classes. Image Credit: genius.com A Sorta Advanced Example: The Guessing Game • The “guessing game” consists of a game object and three player objects. The game generates a random number between 0-9 and the players attempt to guess it. • Three classes: GuessGame.class, Player.class, GameLauncher.class • Game Logic: – The GameLauncher class is where the game starts – it has the main() method – In the main() method, a GuessGame object is created, and its startGame method is called. – The GuessGame object’s startGame method is where the entire game is played. It creates 3 players, picks a number, asks players to guess, checks guesses, and prints out information 2 A Sorta Advanced Example: The Guessing Game run: I’m thinking of a number between 0 and 9... Number to guess is 5 I’m guessing 9 I’m guessing 5 I’m guessing 8 Player one guessed 9 Player two guessed 5 Player three guessed 8 We have a winner! Player one got it right? false Player two got it right? true Player three got it right? false Game is over. BUILD SUCCESSFUL (total time: 0 seconds) Image Credit: nevertheclouds.wordpress.com Garbage Collection In Java • When objects are created in Java, they is placed in an area of memory called “The Heap”. • All objects no matter when or where they are created live in The Heap. • Real name of the The Heap: The Garbage Collectible Heap. • When an object is created, Java allocates memory space on the heap according to how much memory that object needs. • When you are done with an object, Java manages your memory for you. Image Credit: newsfeed.time.com Garbage Collection In Java • When JVM “sees” that an object will never be used again, that object becomes eligible for garbage collection. • When you run low on memory, everything stops and the garbage collector runs and throws out unreachable objects to free up memory so that it can be reused. Image Credit: physics1.blog.ir What Is A Java Program? • Basically, a Java program is a bunch of classes. • One of these classes must have a main() method that can be used to start the program. • All application files can be placed into a Java Archive (.jar) file. • A .jar file contains a manifest file that defines which class in the .jar holds the main() method Image Credit: www.softpedia.com How To Create A Java Archive File (JAR) • A JAR file is simply a single file that contains multiple Java class files. • You will be submitting your homework as a single JAR file. • In Eclipse you select: File -> Export -> Java – Select “Export Java source files and resources” – Provide file name Image Credit: https://www.winzip.com/en/features/archive-file.html Quick Review 1. Object-oriented programming lets you extend a program without having to touch previously tested, working code. 2. All Java code is defined in a class. 3. A class describes how to make an object of that class type. A class is like a blueprint. 4. An object can take care of itself; you don’t have to know or care how the object does it. 5. An object knows things and does things. 6. Things an object knows about itself are called instance variables. They represent the state of an object. 7. Things an object does are called methods. 8. They represent the behavior of an object. 9. When you create a class, you may also want to create a separate test class which you’ll use to create objects of your new class type. 10. A class can inherit instance variables and methods from a more abstract superclass. 11. At runtime, a Java program is nothing more than objects ‘talking’ to other objects. Image Credit: www.globalnpsolutions.com Today’s In-Class Programming Challenge • You’ve decided to upgrade the radio in your 1971 Pinto. You are going to add a tape player. • You need a control system for this new tape player. • Create two Java classes: TapeDeck and TapeDeckTestDrive. • TapeDeck has two methods – playTape, when called, reports “tape playing” – recordTape, when called, reports “tape recording“ • TapeDeckTestDrive will create an object of type TapeDeck and will then call playTape and recordTape Image Credit: www.cbsnews.com Your Homework (due next class) • Add two more methods to TapeDeck: – rewind, when called, reports “rewinding” – ejectTape, when called, reports “tape ejected” • TapeDeckTestDrive will create an object of type TapeDeck and will then call playTape, recordTape, rewind, and ejectTape Image Credit: https://daily.jstor.org/what-made-the-pinto-such-a-controversial-car/ What We Covered Today 1. Creating a Class 2. Creating an Object 3. Garbage Collection Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Declaring a variable 2. Primitive types 3. Java keywords 4. Reference variables 5. Object declaration and assignment 6. Objects on the garbage-collectible heap 7. Arrays (a first look) Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java Lecture #4: Know Your Variables How To Get In Touch With The TAs Ashik Barua ashikbarua@mail.usf.edu EMB 325 Monday/Wednesday : 2:30 pm - 5:00 pm (ENG 233) Tuesday/Thursday: 11:00 am - 12:30 am (ENB 216) Set up an appointment!!! Qi Zheng qizheng@mail.usf.edu ENB 325 MW 12:30pm - 2:30pm 2 Image Credit: https://www.dckids.com/teen-titans-go/robin When you design a class... ● When you design a class, think about the objects that will be created from that class type ● Things that an object knows about itself are called an instance variables. They represent an object’s state (the data), and can have unique values for each object of that type. ● You can think of an instance as another way of saying object. ● Things that an object can do are called methods. ● Objects have instance variables and methods, but those instance variables and methods are designed as part of the class. Image Credit: www.atlantawebdesignga.com When you design a class... ● A class is not an object. (but it’s used to construct them) ● A class is a blueprint for an object. It tells the virtual machine how to make an object of that particular type. ● Each object made from that class can have its own values for the instance variables of that class. [Example: each object of the movie class has a different value for the title variable] ● So what does it take to create and use an object? You need two classes. One class for the type of object you want to use (Dog, AlarmClock, Television, etc.) and another class to test your new class. ● The tester class is where you put the main method, and in that main() method you create and access objects of your new class type. ● The tester class has only one job: to try out the methods and variables of your new object Image Credit: thenextweb.com class type. Object Creation Example 1. Start: Define your class (Dog) 2. Write a tester (TestDrive) class 3.In your tester, make an object and access the object’s variables and methods 1 The Dot Operator (.) ● The dot operator (.) gives you access to an object's state and behavior (instance variables and methods). // make a new object Dog d = new Dog(); // tell it to bark by using the dot operator on the // variable d to call bark() d.bark(); // set its size using the dot operator d.size = 40; Image Credit: newzar.wordpress.com Quick! Get Out Of Main! ● As long as you're in main (), you're not really in Objectville. It's fine for a test program to run within the main method, but in a true 00 application, you need objects talking to other objects, as opposed to a static main() method creating and testing objects. ● The two uses of Main: . to test your real class . to launch/start your Java application ● A real Java application is nothing but objects talking to other objects. ● In this case, talking means objects calling methods on one another. Image Credit: 9stucks.com Know Your Variables ● Java cares about type. It won't let you do something bizarre and dangerous like stuff a Giraffe reference into a Rabbit variable ● And it won't let you put a floating point number into an integer variable, unless you acknowledge to the compiler that you know you might lose precision (like, everything after the decimal point). ● The compiler can spot most problems: Rabbit hopper = new Giraffe ( ); ● Don't expect that to compile. Thankfully. Image Credit: utahscience.oremjr.alpine.k12.ut.us Declaring A Variable ● For all this type-safety to work, you must declare the type of your variable. Is it an integer? a Dog? A single character? Variables come in two flavors: primitive and object reference. ● Primitives hold fundamental values (think: simple bit patterns) including integers, booleans, and floating point numbers. Object references hold references to objects ● Regardless of the type, you must follow two declaration rules: ● variables must have a type ● variables must have a name The Starbucks Guide To Variables ● When you think of Java variables, think of cups. Java Integers ● A variable is just a cup. A container. It holds something. ● It has a size, and a type. ● In Java, primitives come in different sizes, and those sizes have names. ● When you declare a variable in Java, you must declare it with a specific type. ● The four containers here are for the four integer primitives in Java. Image Credit: en.wikipedia.org The Starbucks Guide To Variables byte 8 ● In Java you also have to give your cup a name. ● Each primitive variable has a fixed number of bits (cup size). ● The sizes for the six numeric primitives in Java are shown above Image Credit: en.wikipedia.org Declaring Variables In Java 8 primitive types of variables: 1. 2. 3. 4. 5. 6. 7. 8. boolean char byte short int long float double Remember by using: Be Careful, Bears Shouldn’t Ingest Large Furry Dogs Image Credit: www.nedarc.org Matching Variable Sizes ● You can't put a large value into a small cup. ● Well, OK, you can, but you'll lose some. ● The compiler tries to help prevent this if it can tell from your code that something's not going to fit in the container (variable/cup) you're using. ● For example, you can't pour an int-full of stuff into a byte-sized container, as follows: int x byte b = x; // won't work! ! Image Credit: openresty.org Assigning Variables ● You can a value to a variable in one of several ways including: ○ type a literal value after the equals sign (x = 12, isGood = true, etc.) ○ assign the value of one variable to another (x = y) ○ use an expression combining the two (x = y + 43) ● In the examples below, the literal values are in bold italics: ○ int size = 32; declare an int named size, assign it the value 32 ○ char initial = “j”; declare a char named initial, assign it the value 'j' ○ double d = 456.709; declare a double named d, assign it the value 456.709 ○ boolean isCrazy; declare a boolean named isCrazy (no assignment) ○ isCrazy = true; assign the value true to the previously-declared isCrazy ○ int y = x + 456; declare an int named y, assign it the value that is the Sum Of whatever x is now plus 456 Image Credit: elaboratumonografiapasoapaso.com Naming Variables ● What can you use as names? ● The rules are simple. You can name a class, method, or variable according to the following rules: ○ It must start with a letter, underscore (_), or dollar sign ○ You can't start a name with a number. ○ After the first character, you can use numbers as well. Just don't start it with a number. ○ It can be anything you like, subject to those two rules, just so long as it isn't one of Java's reserved words. Image Credit: code.tutsplus.com Variable Naming Conventions • Camel Case: numBottles, typeOfBook • Pascal case: NumBottles, TypeOfBook • Snake Case: num_bottles, type_of_book • Darwin Case: Num_Bottles, Type_of_Book 16 Image Credit: https://cloudhotshot.wordpress.com/2017/01/03/azure-best-practices-resource-naming-conventions/ Controlling Your Dog Object ● You know how to declare a primitive variable and assign it a value. ● But now what about non-primitive variables? In other words, what about Objects? ● There is actually no such thing as an object variable. ● There's only an object reference variable. ● An object reference variable holds bits that represent a way to access an object. ● It doesn't hold the object itself, but it holds something like a pointer. Or an address. Except, in Java we don't really know what is inside a reference variable. ● We do know that whatever it is, it represents one and only one object. And the JVM knows how to use the reference to get to the object. Image Credit: www.fastcodesign.com Controlling Your Dog Object ● You can't stuff an object into a variable. We often think of it that way... we say things like, "I passed the String to the System.out.println() method." ● Or, The method returns a Dog", or, "I put a new Foo object into the variable named myFoo." ● But that's not what happens. There aren't giant expandable cups that can grow to the size of any object. ● Objects live in one place and one place only—the garbage collectible heap! ● Although a primitive variable is full of bits representing the actual value of the variable, an object reference variable is full of bits representing a way to the object. Image Credit: www.playbuzz.com Controlling Your Dog Object ● You use the dot operator (.) on a reference variable to say, "use the thing before the dot to get me the thing after the dot." ● For example: myDog. bark ( ) ; means, "use the object referenced by the variable myDog to invoke the bark() method." ● When you use the dot operator on an object reference variable, think of it like pressing a button on the remote control for that object. Image Credit: 3milliondogs.com Creating An Object 1. Declare a reference variable: Tells the JVM to allocate space for a reference variable, and names that variable myDog. The reference variable is, forever, of type Dog. 2. Create an object: Tells the JVM to allocate space for a new Dog object on the heap. 3. Link the object and the reference: Assigns the new Dog to the reference variable myDog. Image Credit: www.careerealism.com Life Of An Object Java Arrays 1. Step 1: Declare an int array variable. An array variable remotely controls an array object. int[] nums; 2. Step 2: Create a new int array with a length of 7, and assign it to the previously declared int[] variable nums nums = new int[7]; 3. Or: int[] nums = new int[7]; 4. Step 3: Give each element in the array an int value. Elements in an int array are just int variables. nums[0] = 6; nums[6] = 1; Note: In Java, an array is an object even though it’s an array of primitives. Image Credit: westcliffblog.com Initializing & Working With Arrays • Arrays can be initialized to values when they are declared String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; int[] myNum = {10, 20, 30, 40}; • To change an element of an array: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; cars[0] = "Opel"; System.out.println(cars[0]); // Now outputs Opel instead of Volvo • To reference an element of an array: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars[0]); • To find out how many elements an array has, use the length property: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars.length); // Outputs 4 Image Credit: https://study.com/academy/lesson/java-array-length-vs-size.html Using Array With Objects 1. Declare a Dog array variable: Dog[] pets; 2. Create a new Dog array with a length of 7, and assign it to the previously declared Dog variable pets: pets = new Dog[7]; Note: the array is empty! You still need to create the objects to place into the array 3. Create new Dog objects, and assign them to the array elements. Note that elements in a Dog array are just Dog reference variables. We still need Dogs! pets[0] = new Dog; pets[6] = new Dog; Image Credit: reflectionsinthewhy.wordpress.com Referencing Objects In An Array ● Dog fido = new Dog(); fido.name = “Fido”; ● We created a Dog object and used the dot operator on the reference variable fido to access the name variable. ● We can use the fido reference to get the dog to bark() or eat() or chaseCat(). fido.bark ( ) fido.chaseCat ( ) Image Credit: beautybarmybird.com Referencing Objects In An Array ● We know we can access the Dog's instance variables and methods using the dot operator, but on what? ● When the Dog is in an array, we don't have an actual variable name (like fido). ● Instead we use array notation (dot operator) on an object at a particular index (position) in the array: Dog[] myDogs = new Dog [3] ; myDogs[0] = new Dog; myDog[0].name = “Fido”; myDog[0].bark = 8; Image Credit: www.scholastic.com Review ● Variables come in two flavors: primitive and reference. ● Variables must always be declared with a name and a type. ● A primitive variable value is the bits representing the value (5, 'a', true, 3.1416, etc.). ● A reference variable value is the bits representing a way to get to an object on the heap. ● A reference variable has a value of null when it is not referencing any object. ● An array is always an object, even if the array is declared to hold primitives. ● There is no such thing as a primitive array, only an array that holds primitives. Image Credit: www.tnooz.com In Class Programming Challenge: Chicken Farming ● You run a chicken farm and you need software to help you keep track of your chickens. You don’t know what type of variables to use so you are doing some experiments. ● Create a 5-member Boolean array called lightsOn. Set items 0, 2, and 4 to true and the others to false. ● Create a 5-member array called henHouses that points to objects of type houseForHens. Each houseForHens has three instance variables: small (byte), medium (short), and large (long). ● Set small to 126, medium to 32,766, and large to 2,147,483,646 for the houseForHens objects that have a matching true lightsOn value. ● Execute a While loop 5 times that checks lightsOn, if true it will increment small, medium, and large and print them out. Image Credit: feelgrafix.com What We Covered Today 1. Designing classes 2. The dot operator 3. Variables 4. Controlling objects 5. Arrays Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Methods use an object’s state 2. Method arguments & return types 3. Pass-by-Value 4. Getters & Setters Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java Lecture #5: How Objects Behave A Gentle Reminder From The USF Office of the Registrar Important dates: January 17: Students’ payment deadline for Spring 2020 classes January 24: Students’ late payment deadline for Spring 2020 classes January 27: Students dropped for failure to pay January 27-February 2: Reinstatement with payment in full February 3-7: Reinstatement with faculty written permission and payment in full After February 7: Reinstatement by approved ARC or Graduate Studies Petition ONLY Students who have a financial aid Tuition Deferment, Veteran’s deferment, Florida Prepaid Plan with available billable hours, or a graduate assistant tuition waiver will not be subject to cancellation. Here is the form that students will submit to the Cashier’s Office (ideally by email) to be reinstated between January 27-February 7: https://www.usf.edu/registrar/documents/forms_2019/readd_request_2019.pdf In Class Programming Assignment: ACME Bank ● The ACME bank wants to attract more customers by creating interactive calculators on their website that allow customers to see what they can do with their money. ● Create a class called DoubleMyMoney with instance variables interestRate and startingAmount. Create Get / Set methods to set the interestRate (6%) and amount of money in the account ($10,000). Create a method doubleTime to calculate the number of years that it will take to double the customer’s money. ● Create a class called UntilIDie with instance variables interestRate and startingAmount. Create Get / Set methods to set the interestRate (5%) and the amount of money in the account ($700,000). Create a method howMuchLeft to calculate how long the money in the account would last if I spent $35,000 each year. Image Credit: moneypet.com Introduction To The JavaDoc Tool • JavaDoc tool is a document generator tool in Java programming language for generating standard documentation in HTML format. • It generates API documentation. • It parses the declarations ad documentation in a set of source file describing classes, methods, and fields. • Before using JavaDoc tool, you must include JavaDoc comments /**………………..*/ providing information about classes, and methods etc. • For creating a good and understandable document API for any java file you must write better comments for every class, method. Image Credit: https://www.konakart.com/documentation/javadoc/ JavaDoc Details Sample JavaDoc Image Credit: https://www.iconfinder.com/icons/459695/data_document_file_extension_format_grid_java_icon Sample JavaDoc Doc Image Credit: https://www.iconfinder.com/icons/1633791/.java_.java_file_java_file_java_icon_java_source_code_java_source_code_file_icon Using Array With Objects 1. Declare a Dog array variable: Dog[] pets; 2. Create a new Dog array with a length of 7, and assign it to the previously declared Dog variable pets: pets = new Dog[7]; Note: the array is empty! You still need to create the objects to place into the array 3. Create new Dog objects, and assign them to the array elements. Note that elements in a Dog array are just Dog reference variables. We still need Dogs! pets[0] = new Dog; pets[6] = new Dog; Image Credit: reflectionsinthewhy.wordpress.com Referencing Objects In An Array ● Dog fido = new Dog(); fido.name = “Fido”; ● We created a Dog object and used the dot operator on the reference variable fido to access the name variable. ● We can reference an object even if it is stored in an array: pets = new Dog[7]; pets[0] = new Dog; pets[0].name = “Fido”; pets[0].bark(); Image Credit: beautybarmybird.com Getting Input From The Keyboard In Java • One of the strengths of Java is the huge libraries of code available to you. This is code that has been written to do specific jobs. • All you need to do is to reference which library you want to use, and then call a method into action. One really useful class that handles input from a user is called the Scanner class. The Scanner class can be found in the java.util library. • To use the Scanner class, you need to reference it in your code. This is done with the keyword import. import java.util.Scanner; • The import statement needs to go just above the Class statement: import java.util.Scanner; public class StringVariables { } • This tells java that you want to use a particular class in a particular library - the Scanner class, which is located in the java.util library. Image Credit: www.omgchrome.com Getting Input From The Keyboard In Java • The next thing you need to do is to create an object from the Scanner class. (A class is just a bunch of code. It doesn't do anything until you create a new object from it.) • To create a new Scanner object the code is this: Scanner user_input = new Scanner( System.in ); • So instead of setting up an int variable or a String variable, we're setting up a Scanner variable. We've called ours user_input. The object we're creating is from the Scanner class. In between round brackets we have to tell java that this will be System Input (System.in). Image Credit: www.techiemum.com Getting Input From The Keyboard In Java • To get the user input, you can call into action one of the many methods available to your new Scanner object. One of these methods is called next. This gets the next string of text that a user types on the keyboard: String first_name; first_name = user_input.next( ); • We can also print some text to prompt the user: String first_name; System.out.print("Enter your first name: "); first_name = user_input.next( ); Image Credit: play.google.com The Problem With Strings • In Java, any input that comes from the keyboard will come in as a string – even if you have read in a number! • This means that you need to be able to convert a string to a number. You do this using the following commands: String number = "10"; int result = Integer.parseInt(number); String number = “7.2”; float f = Float.parseFloat(number); Image Credit: http://inmyownterms.com/conversion-tools-and-difference-checkers-for-language-lovers/ Object Behavior ● Remember: a class describes what an object knows and what an object does ● A class is the blueprint for an object. When you write a class, you're describing how the JVM should make an object of that type. ● You already know that every object of that type can have different instance variable values. ● But what about the methods? ● Can every object of that type have different Method behavior? ● Well... sort of. Every instance of a particular class has the same methods, but the methods can behave differently based on the value of the instance variables. Image Credit: www.lookfordiagnosis.com Object Behavior class Mobility { void movement(age) { if (age < 6) {System.out.printlin(“I crawl.”);} if (age < 30) {System.out.printlin(“I run.”);} if (age < 60) {System.out.printlin(“I walk.”);} if (age < 90) {System.out.printlin(“I walk with a cane.”); } } class GetThere { public static void main (String[] args) { Mobility moveMe = new Mobility(); moveMe.movement(20); } Image Credit: rightresponse.org You Can Send Things To A Method ● Just as you expect from any programming language, you can pass values into your methods. ● You might, for example, want to tell a Dog object how many times to bark by calling: d.bark(3) ; ● Let us agree: A method uses parameters. ● Let us agree: A caller passes arguments. ● Arguments are the things you pass into the methods. An argument lands into a Parameter. ● A parameter is nothing more than a local variable. A variable with a type and a name, that can be used inside the body of the method. ● But here's the important part: If a method takes a parameter, you must pass it something. And that something must be a value of the appropriate type. Image Credit: depositphotos.com You Can Get Things Back From A Method ● Methods can return values. ● Every method is declared with a return type, but until now we've made all of our methods with a void return type, which means they don't give anything back: void go() ● But we can declare a method to give a specific type of value back to the caller, such as: int giveSecret ( ) { return 42; } ● If you declare a method to return a value, you must return a value of the declared type! Image Credit: blog.pcb.ca You Can Send More Than One Thing To A Method ● Methods can have multiple parameters. ● Separate them with commas when you declare them, and separate the arguments with commas when you pass them. ● Most importantly, if a method has parameters, you must pass arguments of the right type and order. ● Example: calling a two-parameter Method, and sending it two arguments. class TestStuff { void takeTwo (int x, int y) { int z = x + y, System.out.println(“Total is” + z); } } void go ( ) { TestStuff t = new TestStuff ( ) ; t.takeTwo(12, 34) ; } Image Credit: www.marketscan.co.uk Java is pass-by-value. That means pass-by-copy. Review ● Classes define what an object knows and what an object does. ● Things an object knows are its instance variables (state). ● Things an object does are its methods (behavior). ● Methods can use instance variables so that objects of the same type can behave differently. ● A method can have parameters, which means you can pass one or more values into the method. ● The number and type of values you pass in must match the order and type of the parameters declared by the method. ● Values passed in and out of methods can be implicitly promoted to a larger type or explicitly cast to a smaller type. Image Credit: www.drwealth.com Review ● The value you pass as an argument to a method can be a literal value (2, 'c', etc.) or a variable of the declared parameter type (for example, x where x is an int variable). ● A method must declare a return type. A void return type means the method doesn't return anything. ● If a method declares a non-void return type, it must return a value compatible with the declared return type. Image Credit: billysbilling.com Common Questions ● Question: Can a method declare multiple return values? Or is there some way to return more than one value? ● Answer: Sort of. A method can declare only one return value. BUT... if you want to return, say, three int values, then the declared return type can be an int array. Stuff those ints into the array, and pass it on back. ● Question: Do I have to return the exact type I declared? ● Answer: You can return anything that can be implicitly promoted to that type. So, you can pass a byte where an int is expected. The caller won't care, because the byte fits just fine into the int the caller will use for assigning the result. You must use an explicit cast when the declared type is smaller than what you're trying to return. Image Credit: www.clipartpanda.com Common Questions ● Question: Do I have to do something with the return value of a method? Can I just ignore it? ● Answer: Java doesn't require you to acknowledge a return value. You might want to call a method with a non-void return type, even though you don't care about the return value. In this case, you're calling the method for the work it does inside the method, rather than for what the method gives returns. In Java you don’t have to assign or use the return value. Image Credit: malonemediagroup.com Getters / Setters ● Getters and Setters let you get and set things. ● Instance variable values, usually. ● A Getter's sole purpose in life is to send back, as a return value, the value of whatever it is that particular Getter is supposed to be Getting. ● It's probably no surprise that a Setter lives and breathes for the chance to take an argument value and use it to set the value of an instance variable. Image Credit: plus.google.com Example Of Getters / Setters Image Credit: www.albany.edu Public, Private, Static • private: Least level of visibility provided. Only the objects of this class can see it. • public: Provides the highest level of visibility to this variable. The scope of the variable (as long as it exists) is not limited to just this class or this package, but any other object even from a different package can use this variable by importing that package/file in it's environment. • static: The variable is common to the entire class, not specific to any object. Image Credit: https://www.youtube.com/watch?v=h_UBnO7qJgc In Class Programming Assignment: ACME Bank ● The ACME bank wants to attract more customers by creating interactive calculators on their website that allow customers to see what they can do with their money. ● Create a class called DoubleMyMoney with instance variables Create Get / Set methods to set the interestRate (6%) and amount of money in the account ($10,000). Create a method doubleTime to calculate the number of years that it will take to double the customer’s money. ● Create a class called UntilIDie with instance variables interestRate and startingAmount. Create Get / Set methods to set the interestRate (5%) and the amount of money in the account ($700,000). Create a method howMuchLeft to calculate how long the money in the account would last if I spent $35,000 each year. Image Credit: moneypet.com What We Covered Today 1. Methods use an object’s state 2. Method arguments & return types 3. Pass-by-Value 4. Getters & Setters Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Encapsulation 2. Using references in an array 3. Homework #1! Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java Lecture #6: How Objects Behave Homework #1 Is Assigned! • Bank of America has decided to replace their old ATM machines. ACME Machines, your employer, has won the contract to create and deliver the 500 new ATM machines that Bank of America is going to need. • At the lead programmer for ACME Machines, it is going to be your responsibility to create the software that the new ATM machine will use. • The ATM machine will attempt to provide every customer with money using the largest available bills assuming that the machine still has enough money to fulfill the request. • The ATM machine should be programmed to display "Wrong PIN", "Unrecognized card", and "Out of money – cannot complete transaction". Image Credit: https://www.bpsands.com/store/genmega-2500-atm-machine/ Encapsulation ● Up until now, we’ve not discussed a major oversight on our part. ● We’ve been exposing our data! ● Right now our data is out there for anyone to see and even touch. ● Exposed means reachable with the dot operator, as in: thecat.height = 27; ● Think about this idea of making a direct change to the Cat object's size instance variable. In the hands of the wrong person, a reference variable is quite a dangerous weapon. ● Because what's to prevent: thecat.height = 0; Image Credit: www.defit.org Encapsulation ● This would be a Bad Thing. ● We need to build setter methods for all the instance variables, and find a way to force other code to call the setters rather than access the data directly. ● If we force everyone to call a setter method, then we can protect the cat’s height from being set to an illegal value: Image Credit: www.deepinopensource.com Hiding Data ● So how exactly do you hide the data? ● With the public and private access modifiers. ● private variables, methods, and class are only accessible on the class on which they are declared ● Classes, methods or data members which are declared as public are accessible from every where in the program. ● You're familiar with public—we use it with every main method. ● Here's an encapsulation starter rule of thumb: mark your instance variables private and provide public getters and setters for access control. Image Credit: www.presentermedia.com Encapsulating The GoodDog Class Image Credit: www.butlercountyhs.org How Do Objects In An Array Behave? ● Answer: Just like any other object. The only difference is how you get to them. ● Let's try calling methods on Dog objects in an array. ● Declare and create a Dog array to hold 7 Dog references. Dog[] pets; pets= new Dog[7]; ● Create two new Dog objects and assign them to the first two array elements. pets[0] = new Dog(); pets[1] = new Dog(); ● Call methods on the two Dog objects: pets[0].setSize(30); int x = pets[0].getSize(); pets[1].setSize(8); Image Credit: nextmaths.blogspot.com Declaring & Initializing Instance Variables ● A variable declaration needs at least a name and a type: int size; String name ; ● You know that you can initialize a value) to the variable at the same time: int size = 420; String name = "Donny"; ● Instance variables are the variabels that are declared within a class, but outside of all of the class’s methods. ● But when you don't initialize an instance variable, what happens when you call a getter method? ● In other words, what is the value of an instance variable before you it? Image initialize Credit: elaboratumonografiapasoapaso.com Declaring & Initializing Instance Variables class PoorDog { Instance Variables private int size; private String name; public int getSize() { return size; } public String getName() { return name; } } Image Credit: code.tutsplus.com Declaring & Initializing Instance Variables ● Instance variables always get a default value. ● If you don't explicitly assign a value to an instance variable, or you don't call a setter method, the instance variable still has a value! ● integers 0 ● floating points 0.0 ● booleans false ● references null Image Credit: blogs.articulate.com The Difference Between Instance and Local Variables Local variables do NOT get a default value! The compiler complains if you try to use a local variable before the variable is initialized. Image Credit: www.defit.org Comparing Variables ● Sometimes you want to know if two primitives are the same. ● That's easy enough, just use the == operator. ● Sometimes you want to know if two reference variables refer to a single object on the heap. ● Easy as well, just use the == operator. Image Credit: es.wikihow.com Comparing Variables ● But sometimes you want to know if two objects are equal. ● And for that, you need the .equals() method. ● The idea of equality for objects depends on the type of object. ● For example, if two different String objects contain the same characters (say, "firetruck"), they are meaningfully equivalent, regardless of whether they are two distinct objects on the heap. Image Credit: www.cartoonstock.com Comparing Variables ● But what about a Dog? ● Do you want to treat two Dogs as being equal if they happen to have the same size and weight? Probably not. ● So whether two different objects should be treated as equal depends on what makes sense for that particular object type. ● We need to understand that the operator is used only to compare the bits in two variables. What those bits represent doesn't matter. The bits are either the same, or they're not. Image Credit: www.ck12.org Enumerations In Java • Enumerations serve the purpose of representing a group of named constants in a programming language. • For example the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. • Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). • Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, etc. Image Credit: https://preschoolinspirations.com/days-of-the-week-songs/ Enumerations In Java // A simple enum example where enum is declared // outside any class (Note enum keyword instead of // class keyword) enum Color { RED, GREEN, BLUE; } public class Test { // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.println(c1); } } Image Credit: https://www.developer.com/java/data/understanding-enumeration-in-java.html In-Class Programing: The Student Database Program You’ll be creating code and delivering to Bad Company which will then add their code and deliver it to the customer. You know that Bad Company does bad things with code. With that in mind, write a program that can create student objects. Each student object can have a first name, last name, year in school (freshman, sophomore, junior, or senior) and an enrolled status: true or false. Create setter methods to set each of these student characteristics. Create a method that will print out the current value of the student’s variables. Image Credit: https://www.clipartkey.com/search/student/ What We Covered Today 1. Encapsulation 2. Using references in an array Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Building the Sink a Dot Com game 2. Starting with the Simple Dot Com game (a simpler version) 3. Writing prepcode (pseudocode for the game) Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java Lecture #6: How Objects Behave Homework #1 Is Assigned! • Bank of America has decided to replace their old ATM machines. ACME Machines, your employer, has won the contract to create and deliver the 500 new ATM machines that Bank of America is going to need. • At the lead programmer for ACME Machines, it is going to be your responsibility to create the software that the new ATM machine will use. • The ATM machine will attempt to provide every customer with money using the largest available bills assuming that the machine still has enough money to fulfill the request. • The ATM machine should be programmed to display "Wrong PIN", "Unrecognized card", and "Out of money – cannot complete transaction". Image Credit: https://www.bpsands.com/store/genmega-2500-atm-machine/ Encapsulation ● Up until now, we’ve not discussed a major oversight on our part. ● We’ve been exposing our data! ● Right now our data is out there for anyone to see and even touch. ● Exposed means reachable with the dot operator, as in: thecat.height = 27; ● Think about this idea of making a direct change to the Cat object's size instance variable. In the hands of the wrong person, a reference variable is quite a dangerous weapon. ● Because what's to prevent: thecat.height = 0; Image Credit: www.defit.org Encapsulation ● This would be a Bad Thing. ● We need to build setter methods for all the instance variables, and find a way to force other code to call the setters rather than access the data directly. ● If we force everyone to call a setter method, then we can protect the cat’s height from being set to an illegal value: Image Credit: www.deepinopensource.com Hiding Data ● So how exactly do you hide the data? ● With the public and private access modifiers. ● private variables, methods, and class are only accessible on the class on which they are declared ● Classes, methods or data members which are declared as public are accessible from every where in the program. ● You're familiar with public—we use it with every main method. ● Here's an encapsulation starter rule of thumb: mark your instance variables private and provide public getters and setters for access control. Image Credit: www.presentermedia.com Encapsulating The GoodDog Class Image Credit: www.butlercountyhs.org How Do Objects In An Array Behave? ● Answer: Just like any other object. The only difference is how you get to them. ● Let's try calling methods on Dog objects in an array. ● Declare and create a Dog array to hold 7 Dog references. Dog[] pets; pets= new Dog[7]; ● Create two new Dog objects and assign them to the first two array elements. pets[0] = new Dog(); pets[1] = new Dog(); ● Call methods on the two Dog objects: pets[0].setSize(30); int x = pets[0].getSize(); pets[1].setSize(8); Image Credit: nextmaths.blogspot.com Declaring & Initializing Instance Variables ● A variable declaration needs at least a name and a type: int size; String name ; ● You know that you can initialize a value) to the variable at the same time: int size = 420; String name = "Donny"; ● Instance variables are the variabels that are declared within a class, but outside of all of the class’s methods. ● But when you don't initialize an instance variable, what happens when you call a getter method? ● In other words, what is the value of an instance variable before you it? Image initialize Credit: elaboratumonografiapasoapaso.com Declaring & Initializing Instance Variables class PoorDog { Instance Variables private int size; private String name; public int getSize() { return size; } public String getName() { return name; } } Image Credit: code.tutsplus.com Declaring & Initializing Instance Variables ● Instance variables always get a default value. ● If you don't explicitly assign a value to an instance variable, or you don't call a setter method, the instance variable still has a value! ● integers 0 ● floating points 0.0 ● booleans false ● references null Image Credit: blogs.articulate.com The Difference Between Instance and Local Variables Local variables do NOT get a default value! The compiler complains if you try to use a local variable before the variable is initialized. Image Credit: www.defit.org Comparing Variables ● Sometimes you want to know if two primitives are the same. ● That's easy enough, just use the == operator. ● Sometimes you want to know if two reference variables refer to a single object on the heap. ● Easy as well, just use the == operator. Image Credit: es.wikihow.com Comparing Variables ● But sometimes you want to know if two objects are equal. ● And for that, you need the .equals() method. ● The idea of equality for objects depends on the type of object. ● For example, if two different String objects contain the same characters (say, "firetruck"), they are meaningfully equivalent, regardless of whether they are two distinct objects on the heap. Image Credit: www.cartoonstock.com Comparing Variables ● But what about a Dog? ● Do you want to treat two Dogs as being equal if they happen to have the same size and weight? Probably not. ● So whether two different objects should be treated as equal depends on what makes sense for that particular object type. ● We need to understand that the operator is used only to compare the bits in two variables. What those bits represent doesn't matter. The bits are either the same, or they're not. Image Credit: www.ck12.org Enumerations In Java • Enumerations serve the purpose of representing a group of named constants in a programming language. • For example the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. • Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). • Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, etc. Image Credit: https://preschoolinspirations.com/days-of-the-week-songs/ Enumerations In Java // A simple enum example where enum is declared // outside any class (Note enum keyword instead of // class keyword) enum Color { RED, GREEN, BLUE; } public class Test { // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.println(c1); } } Image Credit: https://www.developer.com/java/data/understanding-enumeration-in-java.html In-Class Programing: The Student Database Program You’ll be creating code and delivering to Bad Company which will then add their code and deliver it to the customer. You know that Bad Company does bad things with code. With that in mind, write a program that can create student objects. Each student object can have a first name, last name, year in school (freshman, sophomore, junior, or senior) and an enrolled status: true or false. Create setter methods to set each of these student characteristics. Create a method that will print out the current value of the student’s variables. Image Credit: https://www.clipartkey.com/search/student/ What We Covered Today 1. Encapsulation 2. Using references in an array Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Building the Sink a Dot Com game 2. Starting with the Simple Dot Com game (a simpler version) 3. Writing prepcode (pseudocode for the game) Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java Lecture #7: Extra-Strength Methods public class ATMCard { Talking About The Homework String cardNum; String cardPIN; float checkingBalance; float savingsBalance; } main CardService / initializeCardDB ATMCard userATMCards[5] CardService / insertCard PIN / processPIN ATMCard ATMCard ATMCard ATMCard ATMCard cardNum cardPIN checkingBal savingsBal cardNum cardPIN checkingBal savingsBal cardNum cardPIN checkingBal savingsBal cardNum cardPIN checkingBal savingsBal cardNum cardPIN checkingBal savingsBal Homework #1 Process Flow Money CardServices initializeCardDB insertCard 2 processCard returnCard 1 4 enterAmount Dispense ATMmachine 3 5 8 7 6 main twenties tens fives ones ATMmachine PIN 3.5 processPIN eatCard verifyBalance verifyMachineBalance In Class Programming Assignment: Little Portal ● You have three arrays of 7 items. First array is numbered 1-7. Second array is numbered A-G. Third array is numbered 8-14. ● When you are dropped into the first array, each item is connected to the second array which is then connected to the third array. A different path leads from the third array back up to the second array back to the first array. ● No matter which location in the first array that you start at, determine the path that it takes to get to location 7 in the first array. ● The forward connections are: 1:B, 2:E, 3:C, 4:A, 5:G, 6:F, 7:D; 8:H, A:9, B:8, C:10, D:13, E:14, F:12, G:11, H:15 The reverse connections are: 9:D, 10:B, 11:F, 12:C, 13:G, 14:E, 15:A, 16:H A:2, B:4, C:5, D:3, E:6, F:1,G:7, H:8 Image Credit: moneypet.com Extra-Strength Methods ● We need more tools. Like operators. We need more operators so we can do interesting things. ● And loops. We need loops. We need for loops. ● Might be useful to generate random numbers. ● And turn a String into an int. ● Why don't we learn it all by building something real, to see what it's like to write (and test) a program from scratch. ● How about a game, like Battleship? Image Credit: www.123rf.com Let’s build a Battleship-style game: “Sink a Dot Com” ● In this game it's you against the computer, but unlike the real Battleship game, in this one you don't place any ships of your own. ● Instead, your job is to sink the computer's ships in the fewest number of guesses. ● Oh, and we aren't sinking ships. We're killing Dot Coms. ● Goal: Sink all of the computer's Dot Coms in the fewest number of guesses. ● You're given a rating or level, based on how well you perform. Image Credit: blog.tesol.org Let’s build a Battleship-style game: “Sink a Dot Com” ● Setup: When the game program is launched, the computer places three Dot Coms on a virtual 7 x 7 grid. ● When that's complete, the game asks for your first guess. ● How you play. We haven't learned to build a GUI yet, so this version works at the command-line. ● The computer will prompt you to enter a guess (a cell), that you'll type at the commandline as "A3", "C5", etc.). ● In response to your guess, you'll see a result at the commandline, either "Hit", "Miss", or "You sunk Pets.com". ● When you’ve sunk three Dot Coms, the game ends by printing out your rating. Image Credit: www.theguardian.com The 7x7 Grid General Flow Of The Game Image Credit: adanai.com A Game Flow Chart Image Credit: www.smartdraw.com Let’s Talk About What Classes We’ll Need ● We're gonna need at least two classes, a Game class and a DotCom class. ● But before we build the Sink a Dot Com game, we'll start with a stripped down, simplified version, Simple Dot ComGame. ● We'll build the simple version, followed by the deluxe version. ● Everything is simpler in this game. Instead of a 2-D grid, we hide the Dot Com in just a single row. ● And instead Of three Dot Corns, we only use one. ● The goal is the same, though, so the game still needs to make a DotCom instance, assign it a location somewhere in the row, get user input, and when all of the DotCom's cells have been hit, the game is over. Image Credit: www.usps.org Let’s Talk About What Classes We’ll Need ● This simplified version of the game gives us a big head start on building the full game. ● If we can get this small one working, we can scale it up to the more complex one later. ● In this simple version, the game class has no instance variables, and all the game code is in the main( ) method. ● In other words, when the program is launched and main() begins to run, it will make the one and only DotCom instance, pick a location for it (three consecutive cells on the single virtual seven-cell row), ask the user for a guess, check the guess, and repeat until all three cells have been hit. Image Credit: nsre.org Let’s Talk About What Classes We’ll Need ● Keep in mind that the virtual row is virtual. ● In other words, it doesn't exist anywhere in the program. ● As long as both the game and the user know that the DotCom is hidden in three consecutive cells out of a possible seven (starting at zero), the row itself doesn't have to be represented in code. ● You might be tempted to build an array of seven ints and then assign the DotCom to three of the seven elements in the array, but you don't need to. ● All we need is an array that holds just the three cells that the DotCom occupies. Image Credit: www.gethow.org Game Play 1. The game starts, and creates ONE DotCom object and gives it a location on three cells in the single row of Seven cells. Instead of "A2", "C4", and so on, the locations are just integers (for example: 1,2,3). 2. Game play begins. Prompt user for a guess, then check to See if it hit any of the DotCom's three cells. If a hit, increment the numOfHits variable. 3. Game finishes when all three cells have been hit (the numOfHits variable value is 3), and tells the user how many guesses it took to sink the DotCom. Image Credit: www.slleisureandculture.co.uk How To Develop A Class 1. Figure out what the class is supposed to do. 2. List the instance variables and methods. 3. Write prepcode for the methods. 4. Write test code for the methods. 5. Implement the class. 6. Test the methods. 7. Debug and reimplement as needed. Image Credit: www.unionsd.org Creating PseudoCode For Our Game Image Credit: www.bfoit.or The Standard For Loop When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop: for (statement 1; statement 2; statement 3) { // code block to be executed } Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed. for (int i = 0; i < 5; i++) { System.out.println(i); } Image Credit: https://www.programiz.com/cpp-programming/for-loop The New Stuff 1. Converting a string to an int: Integer.parseInt(“3”) 2. The for loop: for (int cell : locationCells) { } The foreach Loops: JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse a complete array sequentially without using an index variable.Declare a new variable to hold an element from the array. Identify the array. Each time through the loop the variable will hold a different element from the array until there are no more elements. 3. The post-increment operator: numOfHits++; 4. Break statement: break; Gets you out of a loop immediately. Image Credit: www.warrenteens.com Creating Test Code First (TDD) Image Credit: checkpointech.com Test code for the SimpleDotCom class Image Credit: slides.com The checkYourself() method Image Credit: www.childswork.com Final Code for SimpleDotComTester Image Credit: www.alten.com Final Code for SimpleDotCom Image Credit: semanticbits.com What’s The Output? ● What should we see when we run this code? ● The test code makes a SimpleDotCom object and gives it a location at 2,3,4. Then it sends a fake user guess of "2" into the checkYouself() method. ● If the code is working correctly, we should see the result print out: Image Credit: www.123rf.com In Class Programming Assignment: Little Portal ● You have three arrays of 7 items. First array is numbered 1-7. Second array is numbered A-G. Third array is numbered 8-14. ● When you are dropped into the first array, each item is connected to the second array which is then connected to the third array. A different path leads from the third array back up to the second array back to the first array. ● No matter which location in the first array that you start at, determine the path that it takes to get to location 7 in the first array. ● The forward connections are: 1:B, 2:E, 3:C, 4:A, 5:G, 6:F, 7:D; 8:H, A:9, B:8, C:10, D:13, E:14, F:12, G:11, H:15 The reverse connections are: 9:D, 10:B, 11:F, 12:C, 13:G, 14:E, 15:A, 16:H A:2, B:4, C:5, D:3, E:6, F:1,G:7, H:8 Image Credit: moneypet.com Little Portal Layout Array #1 Array #2 Array #3 Array #2 B E 9 8 10 D B 2 4 C A G F D A 13 14 12 11 15 F C G E A H 5 3 6 1 7 8 What We Covered Today 1. Building the Sink a Dot Com game 2. Starting with the Simple Dot Com game (a simpler version) 3. Writing prepcode (pseudocode for the game) Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Generating random numbers 2. Getting user input from the command-line 3. Looping with for loops 4. Casting primitives from a large size to a smaller size 5. Converting a String to an int Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java Lecture #8: Extra-Strength Methods In Class Programming Assignment: Drone Commander ● The capital of Afganstan, Kabul is located at 34.53 N / 69.17 E. ● As the local drone commander, you are responsible for a fleet of 5 drones that are assigned to travel to locations and take pictures. ● Enter a starting date for your missions in (dd/mm/yyyy) format and time (hh) in 24-hour format. ● Calculate two random numbers between 0-5 degrees and add them to the location of Kabul. Send a drone there to take photographs. It has a 75% chance of being successful – calculate if the mission was a success. ● Drones are complicated machines. You can only fly one every hour. Print out each of the drones used, the date/time it left, where it went, and if successful. Image Credit: forbes.com Homework #1: The Power Of The Print Statement • When your program is not working correctly, you want to find out what is going on. • A great way to do this is to inspect what the variables are currently set to. • You can find out what a variable’s value is by adding a print statement to your program. • Once the problem has been fixed, you can delete the print statement. 3 Image Credit: https://www.poweragency.com/ Prepcode for the SimpleDotComGame Class ● There are some things you'll have to take on faith. ● For example, we have one line of prepcode that says, "GET user input from command-line". ● That means you get to ask some other class/object to do something for you, without worrying about how it does it. ● When you write prepcode, you should assume that somehow you'll be able to do whatever you need to do, so you can put all your brainpower into working out the logic. Image Credit: www.museumofplay.org Prepcode For The SimpleDotCom Game Class Image Credit: uniquehow.com 2 New Java Commands Image Credit: stickylipsbbq.com The Game’s main() Method ● Just as you did with the SimpleDotCom class, be thinking about parts of this code you might want (or need) to improve. Image Credit: www.arearugsclub.com One Last Class: GameHelper ● We made the dot com class. ● We made the game class. ● All that' s left is the helper class the one with the getUserInput() method. ● The code to get command-line input is more than we want to explain right now. It opens up way too many topics best left for later. Image Credit: tommcfarlin.com Running The Game Image Credit: teespring.com Regular (Non-Enhanced) For Loops ● What it means in plain English: "Repeat 100 times.“ ● How the compiler sees it: ○ create a variable i and set it to 0. ○ repeat while i is less than 100. ○ at the end of each loop iteration, add 1 to i ● Part One: initialization ○ Use this part to declare and initialize a variable to use within the loop body. You'll most often use this variable as a counter. ● Part Two: boolean test ○ This is where the conditional test goes. Whatever's in there, it must resolve to a boolean value (true or false). You can have a test, like (x 4), or you can even invoke a method that returns a boolean. ● Part Three: iteration expression ○ In this part, put one or more things you want to happen with each trip through the loop. Keep in mind that this stuff happens at the end of each loop. Image Credit: blog.hubspot.com Trips Through A Loop Image Credit: logos.wikia.com Difference Between For and While ● A while loop has only the boolean test; it doesn't have a built-in initialization or iteration expression. ● A while loop is good when you don't know how many times to loop and just want to keep going while some condition is true. ● But if you know how many times to loop (e.g. the length of an array, 7 times, etc.), a for loop is cleaner. ● Here's the previous loop rewritten using while: Image Credit: www.clipartpanda.com Pre and Post Increment/Decrement Operator ● The shortcut for adding or subtracting 1 from a variable: x++; ● is the same as: x = x + 1; ● And: x--; ● is the same as: x = x - 1; ● The placement of the operator (either before or after the variable) affects the result. Putting the operator before the variable (for example, ++x), means, "first, increment x by 1, and then use this new value of x." This matters when the ++x is part of a larger expression rather than just in a single statement. Image Credit: www.zazzle.com.au Pre and Post Increment/Decrement Operator ● int x = 0; int z = ++x; produces: x is 1, z is 1 ● But putting the ++ after the x give you a different result: ● int x = 0; int z = x++; produces: x is 1, but z is 0! Image Credit: www.123rf.com The Enhanced For Loop ● Beginning with Java 5.0 (Tiger), the Java language has a second kind of for loop called the enhanced for (or foreach for), that makes it easier to iterate over all the elements in an array or other kinds of collections. ● That's really all that the enhanced for gives you—a simpler way to walk through all the elements in the collection, but since it's the most common use of a for loop, it was worth adding it to the language. Image Credit: www.baynote.com The Enhanced For Loop ● What it means in plain English: "For each element in nameArray, assign the element to the 'name' variable, and run the body of the loop." ● How the compiler sees it: ○ Create a String variable called name and set it to null. ○ Assign the first value in nameArray to name. ○ Run the body of the loop (the code block bounded by curly braces). ○ Assign the next value in nameArray to name. ○ Repeat while there are still elements in the array. Image Credit: djtechtools.com The Enhanced For Loop ● Part One: iteration variable declaration ○ Use this part to declare and initialize a variable to use within the loop body. With each iteration of the loop, this variable will hold a different element from the collection. The type of this variable must be compatible with the elements in the array! For example, you can't declare an int iteration variable to use with a String[] array. ● Part Two: the actual collection ○ This must be a reference to an array or other collection Image Credit: kathykwylie.com Converting A String To An Int int guess = Integer.parseInt (stringGuess) ; ● The user types his guess at the command line, when the game prompts him. That guess comes in as a String (“2”, “0”, etc.), and the game passes that String into the checkYourself() method. ● But the cell locations are simply ints in an array, and you can't compare an int to a String. ● For example, this won't work: String num = "2"; int X = 2; if (x == num) // horrible explosion! Image Credit: www.medicalpracticetrends.com Converting A String To An Int ● So to get around the whole apples and oranges thing, we have to make the String "2" into the int 2. Built into the Java class library is a class called Integer (that's right, an Integer class, not the int primitive), and one of its jobs is to take Strings that represent numbers and convert them into actual numbers. Image Credit: mashable.com Casting Primitives ● To force the compiler to jam the value of a bigger primitive variable into a smaller one, you can use the cast operator. It looks like this: long y = 42; // so far so good int x = (int) y; // x = 42 cool! ● Putting in the cast tells the compiler to take the value of y, chop it down to int size, and set x equal to whatever is left. If the value of y was bigger than the maximum value of x, then what's left will be a weird (but calculable') number. long y = 40002; // 40002 exceeds the 16—bit limit of a short short x = (short) y; // x now equals —25534! Image Credit: filmdayton.com Casting Primitives ● Still, the point is that the compiler lets you do it. And let's say you have a floating point number, and you just want to get at the whole number (int) part of it: float f = 3.14f; int x = (int) f; // x will equal 3 Image Credit: 09nearyw.wordpress.com In Class Programming Assignment: Drone Commander ● The capital of Afganstan, Kabul is located at 34.53 N / 69.17 E. ● As the local drone commander, you are responsible for a fleet of 5 drones that are assigned to travel to locations and take pictures. ● Enter a starting date for your missions in (dd/mm/yyyy) format and time (hh) in 24-hour format. ● Calculate two random numbers between 0-5 degrees and add them to the location of Kabul. Send a drone there to take photographs. It has a 75% chance of being successful – calculate if the mission was a success. ● Drones are complicated machines. You can only fly one every hour. Print out each of the drones used, the date/time it left, where it went, and if successful. Image Credit: forbes.com What We Covered Today 1. Generating random numbers 2. Getting user input from the command-line 3. Looping with for loops 4. Casting primitives from a large size to a smaller size 5. Converting a String to an int Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Analyzing the bug in the simple DotCom game. 2. ArrayList Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ An Introduction To Solving Problems Using Java Lecture 9: Using the Java Library, Part 1 Cheating On Homeworks Your homework is very much like your signature – unique to everyone… 2 Image Credit: https://www.rccaraction.com/everybodys-cheating/#outer-popup A Note On Comparing Strings In Java • Given the following code: String a="Test"; String b="Test"; • If you wanted to test to see if the strings were equal, you might try: if(a==b) ===> true (sometimes) • However, if you had this code, you’d get a different answer: String a="test"; String b=new String("test"); if (a==b) ===> false • What’s going on? In this case for new String("test") the statement new String will be created on the heap, and that reference will be given to b, so b will be given a reference on the heap, not in String pool. Now a is pointing to a String in the String pool while b is pointing to a String on the heap. Because of that we get: if(a==b) ===> false. “==“ only works because when you create any String literal, the JVM first searches for that literal in the String pool, and it MAY find a match. • Correct thing to do: if (a.equals(b))  true (always) Image Credit: https://www.sellerexpress.com/comparing-the-costs-of-selling-on-amazon-and-ebay/ Notes On Formatted Printing In Java • Java functions can be used to deliver formatted output. • This allow you to control how much space a decimal or a real number takes up and how many digits are printed out when you print a real number. // A Java program to demonstrate working of printf() in Java class JavaFormatter1 { public static void main(String args[]) { int x = 100; System.out.printf("Printing simple integer: x = %d\n", x); // this will print it upto 2 decimal places System.out.printf("Formatted with precision: PI = %.2f\n", Math.PI); float n = 5.2f; // automatically appends zero to the rightmost part of decimal System.out.printf("Formatted to specific width: n = %.4f\n", n); n = 2324435.3f; Printing simple integer: x = 100 Formatted with precision: PI = 3.14 Formatted to specific width: n = 5.2000 Formatted to right margin: n = 2324435.2500 // here number is formatted from right margin and occupies a // width of 20 characters System.out.printf("Formatted to right margin: n = %20.4f\n", n); } } In Class Programming Assignment: The Maître d‘ Problem ● You are the Maître d‘ at the fancy “Table d‘Or” restaurant. It is important that you know at all times how many of your customers are waiting on their food. ● Create a Java program to keep track of the size of each party in the restaurant. ● Initialize your party size tracking system to: 2,2,4,2,6,3,8,1,2,5,2,3,9,5,3,2,2,7,4,3,10,5 ● Assume that four parties leave (oldest first) and two more arrive: 4,3. ● Questions: how many parties of two are waiting for food? What is your largest party size? Total number of people waiting? How long until the party of 7 gets served? Are there still any parties of 8 on your list? Image Credit: moneypet.com Using the Java Library ● Java ships with hundreds of pre-built classes. ● You don't have to reinvent the Wheel if you know how to find what you need in the Java library, known as the Java API. ● You’ve got better things to do. ● If you're going to write code, you might as well write only the parts that are truly custom for your application. ● The core Java library is a giant pile of classes just waiting for you to use like building blocks, to assemble your own program out of largely pre-built code. ● The Java API is full of code you don't have to type. ● All you need to do is learn to use it. Image Credit: www.dreamstime.com The Switch Statement • Another way to control the flow of your programs is with something called a switch statement. • A switch statement gives you the option to test for a range of values for your variables. • They can be used instead of long, complex if … else if statements. The structure of the switch statement is this: switch ( variable_to_test ) { case value: code_here; break; case value: code_here; break; default: values_not_caught_above; } Image Credit: www.eldontaylor.com The Roomate Food Problem • You and your roomates have agreed that different people will cook different food on different days of the week. • You will create a Java program that will help everyone keep track of what they are supposed to do on a given day of the week. • The assignments are: Monday, Joe cooks spaghetti, Tuesday Mary makes pizza, Wednesday Bob prepares hotdogs, Thursday Amy cooks soup, on Friday Tim grills steak, on Saturday Mary cooks lasagna, and on Sunday Joe creates tacos. Image Credit: https://3docean.net/item/cartoon-food-pack-3d-model/22373773 Bug From Last Time Image Credit: pngimg.com Where’s The Problem? Image Credit: all-free-download.com How Do We Fix It? ● We need a to know whether a cell has already been hit. ● Let's run through some possibilities, but first, let’s look at what we know so far... ● We have a virtual row of 7 cells, and a Dotcom Will occupy three consecutive cells somewhere in that row. This virtual row shows a Dotcom placed at cell locations 4, 5 and 6: Image Credit: danielryanday.com How Do We Fix It? ● The Dotcom has an instance variable—an int array—that holds that Dotcom object's cell locations: Image Credit: www.makeuseof.com Solution Option #1 ● We could make a second array and each time the user makes a hit, we store that hit in the second array, and then check that array each time we get a hit, to see if that cell has been hit before. Image Credit: keebar.com Problem: Option one is too clunky ● Option one seems like more work than you’d expect, It means that each time the user makes a hit, you would have change the state of the second array (the “hitCells” array), but first you would have to check the “hitCells” array to see if that cell has already been hit anyway. ● It would work, but there's got to be something better... Image Credit: crooksandliars.com Solution Option #2 ● We could just keep the one original array, but change the value of any hit cells to -1. That way we only have one array to check and manipulate. Image Credit: www.123rf.com Option #2 is a little better, but still pretty clunky ● Option two is a little less clunky than option one, but it's not very efficient. you'd still have to loop through all three slots (index positions) in the array, even if or more are already invalid because they’ve been “hit” (and have a -1 value). ● There has to something better... Image Credit: www.micrologik.fr Solution Option #3 ● We delete each cell location as it gets hit. and then modify the array to be smaller. Except arrays can't change their size, so we have make a new array and copy the remaining cells from the old array into the new smaller array. Image Credit: www.123rf.com Updating The Pseudocode Image Credit: www.bfoit.org If Only There Was An Array That Could Shrink... ● There really is such a thing. ● But it's not an array, it's an ArrayList. ● A class in the core Java library (the API). ● The Standard Edition ships with hundreds of pre-built classes. ● These built-in Classes are already compiled. That means no typing. ● You need to add the code: import java.util.ArrayList; Image Credit: www.ibook3d.com Some Things You Can Do With An ArrayList ● Make one import java.util.ArrayList; // import the ArrayList class ArrayList myList = new ArrayList(); ● Put something in it Egg s = new Egg(); myList.add(s) ; ● Put another thing in it Egg b = new Egg() ; myList. add (b) ; Image Credit: www.boundless.org Notes On Adding Things To An ArrayList • The java.util.ArrayList.add(int index, E element) method inserts the specified element E at the specified position in this list. • It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices). • Throws IndexOutOfBoundsException if the specified index is out of range: greater than (index size()). Image Credit: https://www.tes.com/lessons/JN71j4qMsuQ4VA/adding-100-and-10s Some Things You Can Do With An ArrayList ● Find out how many things are in it int theSize = myList.size() ; ● Find out if it contains something boolean isIn = myList.contains (s); ● Find out where something is (i.e. its index) int idx = myList.indexOf(b); ● Find out if it’s empty boolean empty = myList.isEmpty() ; ● Remove something from it myList.remove (s) ; Image Credit: www.reallyusefulthings.com How Do You Get Things Out Of An ArrayList? • In an array, information can be retrieved like this: myCard = cardNum[0]; • In an ArrayList, information is retrieved like this: myCard = cardNum.get(0); • Note that in both cases 0 is the location of the data to be retrieved. Image Credit: https://www.shutterstock.com/search/claw+game Comparing An ArrayList To A Regular Array Image Credit: anyaworksmart.com Comparing ArrayList to a Regular Array ● A plain old array has to know its size at the time it's created. ● But for ArrayList, you just make an Object of type ArrayList. Even time. It needs to know how big it should be, because it grows and shrinks as objects are added or removed from it. ○ new String[2] ○ new ArrayList() ■ No size required; however, you can include one if you want to. Image Credit: blog.socialrank.com Comparing ArrayList to a Regular Array • To put an object in a regular array, you must assign it to a specific location. • (An index from 0 to one less than the length of the array.) myList[1] = b; • If that index is outside the boundaries of the array (like, the array was declared with a size of 2, and now you're trying to assign something to index 3), it blows up at runtime. • With ArrayList, you can specify an index using the add(anInt, anObject) or you can just keep saying add(anObject) and the ArrayList will keep growing to make room for the new thing myList.add(b); Image Credit: danpetrosini.com Comparing ArrayList to a Regular Array ● Arrays use array syntax that's not used anywhere else in Java. ● But ArrayLists are plain old Java objects, so they have no special syntax: mylist[1] Image Credit: www.monarchdigital.com Comparing ArrayList to a Regular Array ● ArrayLists in Java 5.0 are parameterized. ● But ArrayLists are plain old Java objects so they have no special syntax. myList[1] ArrayList Note: the is a type parameter. ArrayList simply means a list of strings. Image Credit: chedva.org In Class Programming Assignment: The Maître d‘ Problem ● You are the Maître d‘ at the fancy “Table d‘Or” restaurant. It is important that you know at all times how many of your customers are waiting on their food. ● Create a Java program to keep track of the size of each party in the restaurant. ● Initialize your party size tracking system to: 2,2,4,2,6,3,8,1,2,5,2,3,9,5,3,2,2,7,4,3,10,5 ● Assume that four parties leave (oldest first) and two more arrive: 4,3. ● Questions: how many parties of two are waiting for food? What is your largest party size? Total number of people waiting? How long until the party of 7 gets served? Are there still any parties of 8 on your list? Image Credit: moneypet.com What We Covered Today 1. Analyzing the bug in the simple DotCom game. 2. ArrayList Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/ What We’ll Be Covering Next Time 1. Fixing the DotCom class code 2. Building the real game: Sink a Dot Com Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/ COP 2510 – Spring 2020 Homework #1 Title: The New ACME Machines ATM Machine Bank of America has decided to replace their old, COBOL programmed, ATM machines. ACME Machines, your employer, has won the contract to create and deliver the 500 new ATM machines that Bank of America is going to need. At the lead programmer for ACME Machines, it is going to be your responsibility to create the software that the new ATM machine will use. Bank of America has provided an overview of how their customers typically interact with an ATM machine. The bank customer enters their card into the machine and then types in their PIN. Bank security then verifies the card. The user selects the account to use (e.g. checking or savings). They then select an amount to withdrawal. Security verifies if the amount is available. The system then makes a decision as to if it is going to provide the money. The ATM provides the funds if possible. The ATM provides a receipt and returns the card to the user. The Java program that you will create to control this ATM machine will start with a main method; however, then control will be transferred to a series of classes. Your program will contain at least the following classes and methods:  Class: ATMCard o (1) Variable: cardNum – holds a single ATM card's ID number o (1) Variable: cardPIN – holds a single ATM card's PIN number o (1) Variable: checking balance – amount of money in this person's checking account o (1) Variable: savings balance – amount of money in this person's savings account  Class: CardServices o (2) Method: initializeCardDB – creates an array containing ATM card numbers and PINs o (3) Method: insertCard – checks to see if the inserted card's ID number is recognized o (6) Method: processCard – allows a user to request funds to withdraw o (12) Method: returnCard - returns the inserted card to the user  Class: PIN o (4) Method: processPIN – compares the entered PIN to the PIN stored for this card o (5) Method: eatCard – if the PIN is incorrectly entered four times, this eats the card o  Class: Security o (9) Method: verityBalance – ensure that the card owner's account has enough money o (10) Method: verifyMachineBalance -- ensure that the ATM machine has enough money  Class: Account o (7) Method: select – determines if the user wants to withdraw from checking or savings  Class: Money o (8) Method: enterAmount – asks user to enter the amount that they want to withdraw  Class: Dispense o (11) Method: ones – dispenses ones o (11) Method fives – dispenses fives o (11) Method: tens – dispenses tens o (11) Method: twenty's – dispenses twenty's You can assume that the ATM has been loaded with $1,000 in the following denominations: 25 $20 bills, 25 $10 bills, 40 $5 bills, and 50 $1 bills. The ATM machine will attempt to provide every customer with money using the largest available bills assuming that the machine still has enough money to fulfill the request – denominations don't matter (i.e. it could use all $1 if that's all that it had left) The ATM machine should be programmed to display "Wrong PIN", "Unrecognized card", and "Out of money – cannot complete transaction". The machine should "eat" the ATM card if the PIN is entered incorrectly 4 times. The machine will be preloaded to recognize the following ATM cards: Card Number PIN Checking Savings 123456789 1111 $550 $1,275 135792468 2097 $90 -1 019283746 6194 $715 -1 675849302 0071 $790 $211 347821904 9871 $113 $78 Note that "-1" means that an account does not exist. Once you've created your ATM machine, simulate the following transactions: 1. John Smith has both a checking and a savings account with BoA. He uses the ATM with card 123456789 and enters PIN 1111. He then requests $250 from his checking account. 2. Amy Rain has accounts at Citi Bank. When he inserts his ATM card into the BoA ATM machine with card ID number 347821905 the ATM machine should reject it. 3. Paul Logan has both a checking and a savings account with BoA. He uses the ATM with card 675849302 and enters PIN 0071. He then requests $500 from his checking account. 4. Tammy Placard only has a checking account. She then uses the ATM with card 135792468, but can't remember her PIN. She tries 2000, 2090, 2077, and 2079. 5. Jill Holland only has a checking account with BoA. She uses the ATM with card 019283746 and enters PIN 6194. She then requests $300 from her checking account. This amount is refused because the machine does not have that much money. She then requests $250 and the machine completes the transaction. Note: You are only permitted to use the Java commands that we have covered in class so far. Yes, there are many more, but no, you can't use them in solving this homework! → Homework Assignment: Submit an electronic copy of your program via the Canvas tool. Assignment Requirements: 1. You are required to submit an electronic copy of your program online via the Canvas tool. 2. Javadoc comments should be included for each class, method, and parameter. Before each method, put the following comment lines: /** * Method Name: xxx * Description: xxx * * @param xxx */ 3. Your code must contain the following comment header: // // COP 2510 – Spring Semester, 2020 // // Homework #1: The New ACME Machines ATM Machine // // (Your Name) // 4. This homework is due at the start of class on Thursday, 02/13/2016.
Purchase answer to see full attachment
User generated content is uploaded by users for the purposes of learning and should be used following Studypool's honor code & terms of service.

Explanation & Answer

Hey am through. The attached file is the Netbea...


Anonymous
Goes above and beyond expectations!

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Related Tags