1 / 34

Java Chapter 2 Basic Applications - Overview

Java Chapter 2 Basic Applications - Overview. Demo A simple application The System object Statements The swing library Message boxes and input windows Literals, Identifiers and variables Using arithmetic expressions Operators, assignments and variables Creating Decision statements

sanroman
Télécharger la présentation

Java Chapter 2 Basic Applications - Overview

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Chapter 2Basic Applications - Overview Demo A simple application The System object Statements The swing library Message boxes and input windows Literals, Identifiers and variables Using arithmetic expressions Operators, assignments and variables Creating Decision statements Relational operators

  2. Printing a line of text // This program prints aline of text // by: Terry Clayton // Aug 25, 2003 public class HelloWorld { public static void main( String args[] ) { System.out.println("Hello\n"); } } • So what are the parts?

  3. Java Comments • // single line comments • /* multiple line comments • more here */ • Why comments? • Convey clearer understanding of a class or method. • Do not over comment • Provide information on authors, dates and history of changes

  4. Making programs readable • Use “white” blank spaces before each class and method definition • Use indentation after each parenthesis • Place comments at beginning of class and method definitions

  5. Defining a class • public class HelloWorld • Notice the user-defined class name “HelloWorld” • User defined names in Java are called identifiers • The words public and class are Java reserved words or key words. • The public class name must be the same as the java file name. • HelloWorld.java

  6. Identifiers • Are created by the programmer for class method and variable names. • They are case sensitive in Java. • Hello and hello are different. • Avoid special characters like $%^ in names. • Can not contain spaces • Use “_” or capitalization to introduce word breaks. • HelloWorld or Hello_World

  7. The main method • This method is the starting point for a java application • All Java applications have a main method it must be declared like this: • public static void main( String args[] )

  8. Calling a method from another object • We can call and use many different methods. Some will be user defined and other will be part of the Java API • System.out.println("Hello\n"); • This is calling the system output stream to print the message “Hello” • The \n is a new line control character. Others are \r \t \\ \” • This output goes to the command window. (your DOS window) • “Hello” is a string literal they must be in double quotes • All together this forms a statement

  9. Statements in Java • Are the commands to perform a single task. • Calling methods in one form of statement. • Executing arithmetic expressions is another form of statement. • Statements must end with a “;” semicolon or the compiler will report an error.

  10. Errors!!! • When we type our programs in we will no doubt enter it 100% correctly. • NOT!!! • So errors are likely. • Syntax error are the most common errors. • They are reported by the compiler. • Others error can occur while the program is running (we will talk about these later)

  11. Compiling the program • Open a dos window • Set the path • Change to the drive and directory where your program is stored • Type: javac HelloWorld.java • This will produce a HelloWorld.class file if it is a clean compile. • Otherwise you will get a list of errors to debug

  12. Once compiled we can Run • To run the Java program • Type: Java HelloWorld in our command window.

  13. Adding to and changing a program • Reopen the source(.java) file with an editor. • Add another print statement. • Save • Compile • And run

  14. Let’s fancy our Java up with a window. // Welcome.java import javax.swing.*; public class Welcome { public static void main ( String arg[]) { JOptionPane.showMessageDialog(null,"Welcome\n"); // This is required with windows based java applications // it terminates the application // without this the program will hang up in older versions System.exit(0); } }

  15. The import statement • Tells the compiler where to find library files. • In this case in the javax.swing package (library) • The java API is huge you can find documentation on it at • java.sun.com/j2se/1.4/docs/api/index.html • If we forget the import statement we will get errors. • Lets demonstrate!!!

  16. Calling a method with arguments JOptionPane.showMessageDialog(null,"Welcome\n"); • This statement calls a method that requires 2 arguments. • Arguments are information passed into a method call. • The first one is null this is a place holder for an argument that we will not use. • The second is a message for our output window.

  17. Structured programming • Remember all structured programming languages have these parts • Sequence - Flow of instructions • Iteration – Repeating instructions • Selection – Conditional statements • Key elements • Variables and expressions • Support for modularization

  18. Now for something less trivial • A program to add integers import javax.swing.*; public class addint { public static void main (String arg[]) { String fnum; String snum; int num1,num2,sum; fnum = JOptionPane.showInputDialog("Enter First Number?"); snum = JOptionPane.showInputDialog("Enter Second Number?"); num1=Integer.parseInt(fnum); num2=Integer.parseInt(snum); sum = num1+num2; JOptionPane.showMessageDialog(null,"The sum is"+sum,"Results", JOptionPane.PLAIN_MESSAGE); System.exit(0); } }

  19. Keywords or Reserved words • import • public • super • while • char • float • double • return • class for int if else extends void …. Can not be used as programmer declared identifier.

  20. Variables and literals • To make the preceding program work we need some way to store the values that will be used in the computation. • String variable can store alpha numeric text and special symbols. • “115”, “Hello”, “Ctow&%//gt12” are all string literals • int – short for integer variable can store integer numbers only. • 3.14 is not an integer 3 is.

  21. Variables and memory • Choose meaningful names • String variable can be large and consume lots of memory. • Each character is stored in unicode (a 2 byte derivation of ascII) • Integer variables are 4 byte in size and store information in binary format.

  22. Other Variables types • String – This is actually a class type • These are all primitive data types • int • short • long • float • double • character • byte • boolean – True or False

  23. Primitive data types • defined by type size and values

  24. Declaring and initializing variables int x = 10; • Or int x; X=10;

  25. Type casting • Converting one type to another • This is need for example • float rad, circ; • circ = (float)Math.PI * rad; • // this type casts double value of Math.PI to a float. • without this a syntax error message will be generated by the compiler. • We can type case and primitive or object type. • We are not required to type cast when converting to a larger storage class. • ie from float to double.

  26. Concatenation • System.out.println(“Hello “ + name ); • System.out.printlin(“Pay = “ + pay); • We can display unicode characters using the \uXXXX escape sequence. • See page 723 for unicode table

  27. Constants • Help to make programs easier to maintain. • Help to make the programs easier to read. • final double TAXRATE = 0.06; • Sales = Amt * quant * ( 1 + TAXRATE);

  28. Dialog boxes • The swing API provides classes and methods for creating and using dialog boxes. • JOptionPane.showInputDialog(“prompt”); • JoptionPane.showMessageDialog( null, “The message”, “Windowtitle”, JoptionPane.INFORMATION_MESSAGE) • ERROR_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE are other options.

  29. Converting String values into integers • numint=Integer.parseInt(numstr) • Integer is a wrapper class. A class implementation of an integer value. • The parseint method converts the string argument to an integer and returns its value.

  30. Calculations - Arithmetic • A = B + C; • Sum = num1 + num2; • These are arithmetic expressions. • Composed of binary operators • = ( assignment ) • + ( addition )

  31. Operators Precedence • Binary Operators: • */%+- • % - Modulus operator (integer division remainder) • From left to right (infix notation) • The equal sign evaluates from right to left • Parenthesis can modify order of operations • A = C * (B + 2) vs A = C * B + 2

  32. The scanner class Import java.util.Scanner; String Name; Scanner linput = new Scanner(System.in) Name = linput.nextLine(); …

  33. Lets write a program • To compute the results of several arithmetic operations.

  34. Homework #2 (CS211/212) • Design, code and test problem 2.6, 2.10 • Due one week after date assigned • Turn in source code and class files on a labeled disk as per syllabus. • jc2e6.java and jc2e10.java • Also turn in class files

More Related