Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java the easy way James A. Rome Tennessee Governor's Academy August 2010.

Similar presentations

Presentation on theme: "Java the easy way James A. Rome Tennessee Governor's Academy August 2010."— Presentation transcript:

1 Java the easy way James A. Rome Tennessee Governor's Academy August 2010

2 Why Java?  Java is the most in-demand language (= job opportunities)  It is a modern object-oriented language  It is similar to C and C++  It leaves out pointers, multiple inheritance, operator overloading  Write once, run anywhere  From supercomputers to cell phones, Macs, Windows, Linux  It is faster than any language other than Fortran or Assembler  There are oodles of libraries  Free excellent development tools

3 Java programmers are in demand Management/Programming- Development-Skills-In-Demand-505665 In the WSJ recently, there was a long article on how the language you use affects how you think. Computer languages foster logical thought. But many scientific calculations do not fit nicely into existing computer languages Remember that digital computers do discrete mathematics and computations: calculations are done at a finite number of points. -> round-off and truncation errors -> most floating point numbers cannot be represented exactly in binary

4 Tools you will need (installed I hope)  The Java development kit ownloads/index-jsp-138363.html ownloads/index-jsp-138363.html  The NetBeans IDE. Some people prefer Eclipse  A programmer's text editor such as  We may get to databases, so I asked for MySQL wnloads wnloads

5 Our foray into Java Purpose: Get your feet wet so you can understand how scientists use computers and teach yourself more Java.  The book is really good, so please read it.  I want to concentrate on what is not in the book  How to do a graphical user interface (GUI)  How to model a real problem and get it into a form a computer can solve  How to teach yourself  Along the way we will use and learn many Java Classes and techniques

6 Some basic syntax  Assignment uses an equals sign  int b = 4; // assigns 4 to the integer variable b  Testing for equality uses ==  if(b == 4) { /* do something when b is 4 */}  // Comments to the end of the line  /*...*/ Comments blocks, which can be many lines  /**... */ A JavaDoc comment  Java is self documenting if you put these comments into your code they get converted to nice html  Formatting is optional but important for readability  All statements must end in a semicolon  Braces {} group lines of code and define a scope  Things defined in the braces are not accessible outside them.  Names must start with a letter

7 Java syntax Built-in types for variables:  char, int, short, byte, long, float, double, boolean  These are not Objects. But all have wrapper classes that turn them into Objects int a = 5; Integer aInt = new Integer(a);  Everything else is an Object (think noun, its a thing)‏  Unlike in C or C++, these are the same on all platforms  Otherwise (without ints, floats,…), you could not write a = b + c;

8 Loops int j = 0; for(int i = 0, j = 5; i < 3; i++) { j += i; // becomes 5, 6, 8 (same as j = j + i)‏ } // j = 8 at end of loop // i no longer defined here because outside the {} while(j < 10) { // Test at start of loop System.out.println("j=" + ++j); // preincrement }// Prints out j=9, j=10 do { // Test at end of loop System.out.println("j=" + j++); } while (j < 20); // prints out j=10,...j=20 starting values do while at end of loop do this Class methods or fields are referenced using "." System.out returns a PrintStream object, which has a method println()

9 Logic (make decisions) int a = 3; while(a < 12) { if(a == 5)‏// == is a test for equality System.out.println("Hit a=5"); else if(a < 10)‏ System.out.println("a < 10"); else System.out.println("a >= 10"); a++; // if you forget this, you get an infinite loop! } // Ternary operator int b = ((a > 7) ? 0 : 1);// Usually a good idea to put if(b != 5) b += 7; // Parens around the condition

10 Case statements char c = 'b'; switch(c) { case 'a': System.out.println("a"); break; // if break is missing, this “falls through” case 'b': System.out.println("b"); break; default: System.out.println("not a or b"); } The argument you switch on must be an int, char, short, or byte. Used to improve logic and speed decision trees with a hash.

11 Everything in Java is part of a class Classes represent objects from the real world. Think of a class as “The definition of a set where each member of the set exhibits the same behavior and has the same attributes and associations.”  Good programmers decide what classes they need to write before starting to write a program!  Classes in Java may have methods and attributes.  Methods define actions that a class can perform.  Attributes (or fields) describe properties of the class  Classes are described in JavaDocs that are generated from comments in your code. (‏  You need to learn what the basic classes do by reading JavaDocs: String, Collection, HashMap, Vector, BufferedReader, BufferedWriter, Integer, Math, File, …  Call with ClassName.method() or ClassName.attribute

12 Creation of a Pet public class Pet { int age; // with no public, private, these are float weight; // these are all protected float height; String color; /** Method to put pet to sleep */ public void sleep() { System.out.println("Good night. See you tomorrow"); } /** Method to feed pet */ public void eat() { System.out.println("Feed me a cookie!"); } /** Method to let pet speak */ public String say(String aWord) { String petResponse = "OK!! OK!! " + aWord; return petResponse; } The returned type file:///home/jar/TGA/Presentations/FermiAc celeration.ppt

13 What is an IDE?  You write, compile, run, and profile your program within the Integrated Development Environment (IDE).  It makes your life simpler:  A code-friendly editor with context highlighting, code hints, and code completion  It makes it really easy to create a graphical user interface  It write lots of boiler-plate code for you  NetBeans is also great for C/C++, Python, Ruby, Fortran  It is extendable with numerous plugins  NetBeans is my favorite IDE by far  You might like Eclipse or JDeveloper

14 NetBeans should be installed  Start NetBeans IDE Start/All Programs/  Tools/Plugins/Insta lled Tab  Make sure that Java SE is activated

15 Set your NetBeans options Under Tools/Options  In General: Pick your favorite Web Browser  Under Options/Formatting, set the indent and tab sizes to 3 characters  You can look at the other options at your leisure

16 Install the JavaDocs  The Java documents come in a zip file: jdk-7u?? [download it from the JDK page]  NetBeans is smart enough to use it in its zipped form, but you might also want to use it in your Web browser, so copy the file from the cd to your Documents folder into a Java subdirectory. Unzip it by double-clicking on it.  Add the zip file to NetBeans Tools, Java Platforms  You could add the source code here also

17 Create a Pet in NetBeans  File/New Project  Create a new Project called “MyPets”  Do not create a Main Class

18 Make a Package for your project A package is a way of specifying a set of classes that have special privileges because they belong with each other.  They avoid name collision  By convention, you use a reverse DN (e.g.,  We will use mypets (in lc)  Right-click the MyPets Source Package name and select “New, Java Package”

19 Create the Pet Class Right-click the mypets Package and select “New, Class” Note that the file is always, and it is stored in the package directory tree By convention, Classes start with an uppercase letter.

20 Pet Code Elements of our class:  Four class attributes  Three class methods  One class constructor In Java, things have visibility:  public — visible and usable to all  private — only accessible by this class  protected (default) —accessible by classes in this package Visibility keeps code clean and secure. If you want something visible, create getter and setter methods  So the attributes are private

21 Classes must be instantiated In order to do anything with a class you must “create an instance of the object.” This uses the class definition to make a copy of the object described by the class and to put it in the computer’s memory. Pet myPet = new Pet(); myPet is the name of the instance and is a member of the class Pet.

22 We need code to instantiate Pet public class PetMaster { public static void main(String[] args) { String petReaction; Pet myPet = new Pet();; petReaction = myPet.speak("Tweet!! Tweet!!"); System.out.println(petReaction); myPet.sleep(); } class signature main method Local variable Make a Pet Call the Pet methods

23 Make a PetMaster Class

24 Run the project The project needs to know where the main() method is. Right-click the Project, and select Properties Note that you must specify the package as well as the class name in the Run settings Run your project by either clicking the green arrow, or selecting Run Main Project on the Run Menu

25 Inheritance Our class Pet will help us learn yet another important feature of Java called inheritance. In real life, every person inherits some features from his or her parents. Similarly, in the Java world you can also create a new class, based on an existing one (but only one). A special keyword extends does the trick: class Fish extends Pet { } Fish is a subclass of the class Pet. Class Pet is a superclass of the class Fish. Fish myLittleFish = new Fish(); myLittleFish.sleep(); (Fish inherits all of the methods of Pet)‏

26 Making a subclass Creation of subclasses in NetBeans is a piece of cake! Right-click the package and select New, Class, and type Fish as the name of the class. Then put in “extends Pet” before the first { Let’s not forget, however, that we’re creating a subclass of a Pet to add some new features that only fish have, and to reuse some of the code that we wrote for a general pet. Everything inherits from Object

27 Fleshing out our Fish public class Fish extends Pet { private int currentDepth = 0; // keeps track of the depth public int dive(int howDeep) { // a new method for fish currentDepth = currentDepth + howDeep; // Incremental System.out.println("Diving for " + howDeep + " feet"); System.out.println("I’m at " + currentDepth + " feet below sea level"); return currentDepth; } @Override // An annotation. This overrides Pet.speak public String speak(String something) { return("Don’t you know fish do not talk!"); }

28 Need to change PetMaster public class PetMaster { public static void main(String[] args) { String petReaction; // Your previous code can stay here....... Fish myFish = new Fish(); myFish.dive(2); myFish.dive(3); petReaction = myFish.speak("Glug"); System.out.println(petReaction); myFish.sleep(); }

29 Run the code again with your fish

30 How to run without NetBeans Taken from README.TXT in the MyPets/Dist folder: When you build an Java application project that has a main class, the IDE automatically copies all of the JAR files on the projects classpath to your projects dist/lib folder. The IDE also adds each of the JAR files to the Class-Path element in the application JAR files manifest file (MANIFEST.MF). To run the project from the command line, go to the dist folder and type the following: java -jar "MyPets.jar" To distribute this project, zip up the dist folder (including the lib folder) and distribute the ZIP file.

31 User interfaces Note the thousands of identical and unlabeled controls © Pixar The cartoon Lifted was shown along with Ratatouille. It is all about user interfaces.

32 It is even worse under pressure © Pixar

33 Making an application with a GUI There are several methods of making graphical user interfaces in Java — AWT, Swing, SWT. We will concentrate on Swing.  Swing is built into all modern JDKs  A Swing book is on your CD  It is an easy-to-use high-level java interface  Swing components are Java Beans  A Java Bean Object has get and set methods  It adheres to certain naming conventions  Java Bean properties can be manipulated in GUIs by tools such as NetBeans  But you must always remember the user!

34 Making a GUI application using NetBeans  Open NetBeans and do File, New Project  Select Java Application from the Wizard and hit Next  Uncheck Create Main Class  Enter the project Name YourName and hit Finish  The YourName project will appear in the left Package Window, with a package, files, and a blank GUI

35 NetBeans has a new GUI framework Make a new Java package Create a new GUI class based upon A JFrame by right-clicking the yourname Package.

36 Your new GUI project Navigator Lets you set parameters of each component and rearrange them Palette has components you can place onto the GUI Set the properties of each com- ponent here

37 Add a prompt label  Click the Label in the Palette (top-right) Swing controls, and then click near the top-left of the design area  Use the dotted guidelines to space from the top and left edges.  Double-click jLabel1 to edit the text and hit Enter (or else it will not "stick") The solid semi-circles indicate that this component is pinned to the edge if the component is resized.

38 Add a TextField for data input  Add a TextField. Note the three spacing option lines and the lower edge alignment markers  Drag the right edge of the TextField to the right edge until the vertical dotted line appears. This pins the field to the right edge.  Double-click “jTextField1”, delete it, and hit Enter. Right-clicking and selecting “Edit text” may work better.  Try to run your project.

39 Rename your swing objects  It is very important to replace the default names in a more complicated project so that you know which text field (or other object) is which.  Right-click each label and change its name  I used “enterNameLabel” and “enterNameTextField”  Note that by convention, variables start with a lower- case letter, and I retained the Swing type in the name  Do this to all your Swing objects in the future...

40 Run the app  Notice how the TextField is pinned to the top and right edges as the window is resized.  Windows Apps do not have this nice property, which is due to using a Layout Manager

41 What is a Java Bean?  A class that exposes its accessor methods:  For each public class member, there is a get and set method  It must be serializable. This allows the instance of the class to be written to a file and read back again.  class ClassName implements Serializable {....}  It must use member names that start with lowercase  private String myString = “Boo!” public String getMyString(void) {return String;} public void setMyString(String s) { myString = s;}  All Swing components are Java Beans  Therefore, we can make our own GUI components by extending a Swing class

42 Eliminate the StatusBar Click StatusPanel and delete it Source view

43 Delete the statusBar code At the end of YourNameView, delete private final Timer messageTimer; private final Timer busyIconTimer; private final Icon idleIcon; private final Icon[] busyIcons = new Icon[15]; private int busyIconIndex = 0; In the constructor, delete all but public YourNameView(SingleFrameApplication app) { super(app); initComponents(); }

44 Fix the App name  Expand the yourname.resources package  Open Application.description  Change the Title (to "Your Name" ) and you can replace the other fields (e.g., Vendor or the Description) if you wish. Save your project

45 Add an OK Button & output Label  Add a Button aligned to the bottom-right edge guides (which pins the button to this corner as the frame is resized).  Rename it to okButton, and change the displayed name to “OK”.  Add a Label for the output text called “outputLabel”. Stretch it to fill the horizontal width up to the right guideline. Delete the text (the label will collapse to a line).  I made the whole frame smaller vertically The Label is pinned to the left edge and the top of the button Save your project

46 Change the font for the outputLabel Double-click the... to open the font dialog. Pick a font you like! Save your project

47 Add an action event to the JButton  The GUI is done, but it does not do anything yet!  An ActionPerformedEvent occurs when a button is pressed. At that point we can get the text the user typed and display it.  Right-click the okButton and add the event. Save your project

48 ActionEvent code Source view w The yellow bars indicate unused imports. Right-click in the code and choose "Fix imports" (They belonged to the progress bar that we deleted.

49 Code completion and JavaDocs helps private void okButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String name = "Your name is " + enterNameTextField.getText(); outputLabel.setText(name); } Save your project Strings are immutable. They are stored and never changed.

50 Run the code Defects in the application:  It would be nice to let the user hit “Enter” in addition to clicking the button  Can make it prettier. (e.g., Colored text)‏  This is a possible security hazard because we do not check what the user typed in. (It would be for sure in a Web Application.)‏

51 Adding a key event private void enterNameTextFieldKeyTyped(java.awt.event.KeyEvent evt) { // TODO add your handling code here: } Right click the enterNameTextField and do Event, Key, keyTyped.

52 Edit the JTextField KeyListener '\n' is generated when the user hits Enter. Note that chars are in single quotes. This code appears twice. It is a good candidate for a new class method. Then any changes to this code only have to be done once. How???? Run your code and verify that hitting Enter is the same as clicking OK

53 Homework assignment Make a Magic Fortune- Telling Machine  Make a fortune-telling GUI– press the button and get an answer.  Answers: Yes, no, maybe, unlikely, focus and ask again, cannot foretell now, looks like yes, indications say yes, consult me later, can't say now, absolutely, chances aren't good, don't bet on it, answer unclear ask me later, prospect good, very likely…  Make your own list  Put in random delays before answering  Put in intermediate messages ("I'm thinking") Code issues:  Will need Math.random()  It returns a double from 0.0 to <1.0  For example, if there are 10 possible answers int j = (int)10.0*Math.random();  Will want to put answers in an array: String [] answers = {"Yes", "No",…}; // 10 entries  So, to get the random answer, just use answers[j]  One way of getting a delay is to make a for loop in which you do something that takes time [e.g., Math.sin()] and repeat it a random number of times.

54 Project: A RPN binary calculator RPN = reverse Polish notation  Easier logic and faster to use  Example: 1+1=2  1 Enter  1+ // the result is displayed  Example: 1 + 5 / 6 = 1  1 Enter  5 +  6 / // the result is displayed  When you start to enter a number, the old result is erased from the field

55 A RPN binary calculator My GUI for RPN Binary Calculator-- you make one you like This has the same components you used in the last project. Questions to ponder: Does the code calculate in binary or decimal? Where does the user enter numbers? What does each button do? How do you handle negative numbers? Do you enter the binary digits from right-to-left, or from left-to-right?

56 Calculator logic  Calculators have at least 2 registers:  Accumulator accepts the current entry  Result stores the running result  The +-*/ keys  They preform their operation: Result +-*/ Accumulator  Display result  Set clear flag and clears if it was on The number keys  If first one, erases display string  Appends number to end of display string  The Enter key  Replaces the result with contents of Accumulator  Sets clear flag  The Clear key  1st: Clears accumulator  2nd: Clears result

57 Code snippets for the calculator // New variables for Class // The accumulator private int accum = 0; // The running result private int result = 0; // The binary answer private String display = ""; private String binaryOut = ""; // Define constant variables for the operations // The entry field needs clearing private boolean clearEntry = true; private void oneButtonActionPerformed(java.awt.event.ActionEvent evt) { if(clearEntry) { clearEntry = false; accum = 0; display = ""; } accum = accum * 2 + 1; display = display + "1"; binaryTextField.setText(display); decimalTextField.setText(new Integer(accum).toString()); } private void clrButtonActionPerformed(java.awt.event.ActionEvent evt)‏ { // Make this so that the first time it is pressed, // it clears the entry, // and the second time it clears everything if(accum != 0)‏ accum = 0; else result = 0; display = ""; decimalTextField.setText(new Integer(accum).toString()); binaryTextField.setText(display); } private void enterButtonActionPerformed(java.awt.event.ActionEvent evt)‏ { result = accum; clearEntry = true; } private void plusButtonActionPerformed( java.awt.event.ActionEvent evt) { // Calculate the result result += accum; clearEntry = true; binaryTextField.setText(toBinary(result)); decimalTextField.setText(new Integer(result).toString()); } /** * Convert a decimal number to binary and return it as a String * @param decimal - the input integer * @return The returned String binary representation of the decimal number */ private String toBinary(int decimal) { String binaryOut = ""; // Convert answer to binary while(true) { binaryOut = decimal%2 + binaryOut; //Move right-to-left decimal /= 2; if(decimal == 0)‏ break; } return binaryOut; }

58 Decimal to binary conversion Suppose we want to convert 9 to binary: Must start with the lowest power of 2(right-most bit)‏  9/2 = 4 with remainder 1  There must be a 1 in 2^0 right-most bit  Divide the number by 2 which moves the binary number one-place to the right, so we are checking the 2^1 place  4/2 = 2 + 0 remainder  There are no 2^1  Answer so far = 01  Divide 4 by 2 again to check the 2^2 place  2/2 = 1 with 0 remainder  No 2^2  Answer = 001  Divide by 2 again to check the 2^3 place  1/2 = 0 with 1 remainder  Answer = 1001

59 Additions and improvements  Handle negative numbers  Need to define the number of allowed places and the sign bit  Will have to check for user input errors!  Still calculate in decimal, but use two's complement in the display  Allow the user to input a positive binary number, but change it to two's complement with a +/- key  Possibly display the current result register  Add a memory register

Download ppt "Java the easy way James A. Rome Tennessee Governor's Academy August 2010."

Similar presentations

Ads by Google