1 / 57

Bobby D. Gerardo Kunsan National University Summer 2004

Programming and Problem Solving Using Java. Bobby D. Gerardo Kunsan National University Summer 2004. Review. Printer. Scanner. Screen. Mouse. Speaker. Floppy disk. Hard disk. CD-ROM. Keyboard. Main Memory. Hardware Computer Components. Secondary storage. Input devices.

chloe-foley
Download Presentation

Bobby D. Gerardo Kunsan National University Summer 2004

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. Programming and Problem Solving Using Java Bobby D. Gerardo Kunsan National University Summer 2004

  2. Review

  3. Printer Scanner Screen Mouse Speaker Floppy disk Hard disk CD-ROM Keyboard Main Memory Hardware Computer Components Secondary storage Input devices Output devices Central Processing Unit Arithmetic and Logic Unit (ALU) Control Unit (CU)

  4. High-Level Languages

  5. C source code C source code C source code C Compiler for Macintosh C Compiler for Sun C Compiler for IBM-PC Object code for Macintosh Object code for IBM-PC Object code for Sun C versus Java Program Translation Java-program translation and execution (platform independent object code) C-program translation (platform dependent object code) Java source code Java Compiler the same for any platform Java Virtual Machine object code (byte code) Macintosh Interpreter IBM-PC Interpreter Sun Interpreter Executable instructions for Macintosh Executable instructions for IBM-PC Executable instructions for Sun

  6. Implementation Code Format public class NameInStars { // Datafields private String name; //input - your name // Methods // Create a new NameInStars object with your name stored. public NameInStars(String nam) { name = nam; } // Surround the name in stars on 3 lines. public String surroundNameInStars() { return “*****” + name + “*****\n” + “*****” + name + “*****\n” + “*****” + name + “*****; } } // Class NameInStars class header line data declaration method definitions

  7. Case Study Solution Format • Problem– specify the problem requirement • Analysis– analyze the problem an identify the classes that will be needed • Design– design the classes to solve the problem. Locate the relevant classes in libraries. Modify existing classes if necessary. Design new classes where necessary • Implementation– implement the new and modified classes. • Testing– test and verify the completed program.

  8. Chapter 2Using Primitive Data Types and Using Classes

  9. 2.1. Primitive Data Types • Data types – • Variables – • Declaration statement -

  10. Table 2.1 Primitive data types and values

  11. Variables • Variable: a kind of data whose content can change during program execution. The type of a variable can be a primitive type or a class. • Data declarations can be used to declare variables.

  12. Examples of Declaring variables • int kids = 2; • double bankBalance = 500.45; • char firstLetter = 'a'; • boolean married = true;

  13. Variable Declaration • Form: typeName variableName[= value]; • Example: int pennies; int kids = 3; • Interpretation: The data type of variableName is specified as typeName where typeName is either predefined in Java or is the name of a class that has been defined by Java programmers. If typeName is a primitive type and value is specified, it must be a literal (constant) of data type typeName. If typeName is a class type and value is specified, it must be a object of data type typeName

  14. Valid and invalid double values Valid Invalid • 3.14159 -15e-0.3(0.3 invalid exponent) • 0.005 12.5e.3(.3 invalid exponent) • .12345.123E3 (needs lowercase e) • 12345.0 e32 (doesn’t start with a digit) • 16. a34e03(doesn’t start with a digit) • 15.0e-04(value is 0.0015) • 2.345e2 (value is 234.5) • 1.15e-3 (value is 0.00115) • 12e+5 (value is 1200000.0)

  15. Some char values • char values are enclosed in apostrophes: ‘a’, ‘A’, ‘*’, ‘3’, ‘‘(space) • Escape characters are a sequence of 2 characters that start with \: • ‘\n’ new-line (start a new output line) • ‘\t’ Tab • ‘\’’ Single quote • ‘\”’Double quote • ‘\\’ Backslash

  16. 2.2 Processing numeric data Arithmeticoperator Meaning Example + Addition 5 + 2 is 75.0 + 2.0 is 7.0 – Subtraction 5 - 2 is 35.0 - 2.0 is 3.0 * Multiplication 5 * 2 is 105.0 * 2.0 is 10.0 / Division 5.0 / 2.0 is 2.55 / 2.0 is 2.55.0 / 2 is 2.55 / 2 is 2 (integer division) % Remainder 7 % 4 is 3 (use only w/ int) 4 % 7 is 4

  17. Integer Division and Remainder • int data type + - * / =(assignment) %Used only with integers, gives remainder • Examples of integer division and remainder 15 / 3 = 5, 15 % 3 = 0 15 / 2 = 7, 15 % 2 = 1 2 / 15 = 0, 2 % 15 = 2 299 / 100 = 2, 299 % 100 = 99

  18. Statements and Expressions • Statement: an instruction that performs an operation. There are two kinds of statements: • data declarations - tell the Java compiler what kind of storage locations to allocate • executable statements - instruct the computer how to process the information in storage • Expression: Java code that produces a result. Expressions are used mostly as parts of statements.

  19. Assignment Statement • Form: variable = expression; • Example:x = y + z; • Interpretation: If variable is declared as a primitive type, the value of the expression is stored in variable. If variable is a declared as a class type, a reference to the object formed by expression is stored in variable. • The previous value ofvariable is lost. • The expression can be a variable, a constant, a literal, a method call returning a value, or a combination of the above connected by appropriate operators (such as +, -, * and / ).

  20. Assignment Compatibility • In an assignment statement, the value of the expression must beassignment compatiblewith the variable, meaning that: • Either the data types of the expression and variable are the same, or • The expression’s type can be converted to the variable’s type. If this condition is met, the conversion (which is named assignment conversion) is performed automatically.

  21. Effect of assignment statements • sum = sum + item; before assignment: sum = 25.0; item = 5.0 after assignment: sum = 30.0; item = 5.0 • newx = -x; before assignment: newx = 0.0; x = -5.123; after assignment: newx = 5.123; x = -5.123;

  22. Data Type of Arithmetic Operation • The type of the result of an arithmetic operation is double if an operand is type double. e.g., 1+ 2.0 is 3.0 • If both operands are type int, then the result is type int. e.g., 1 / 2 is 0.

  23. Mixed-type assignments • Mixed-type assignment statement: the assignment of an expression of one type to a variable of another type. • Assignment conversion: automatic conversion of the expression value (after the expression was completely evaluated) to the variable type. Such a conversion must be a widening one (e.g., from int to double). int m = 3; int n = 2; double x, y; y = m + n; assignment conversion: y becomes 5.0 (not 5) x = y + m / n; m / n is 1 (not 1.5), 5.0 + 1 is 6.0, assign 6.0 to x • Example of invalid assignments due to possible loss of the fractional part (narrowing conversion is not allowed) int count; count = 3.6; invalid: can’t assign double to int count = count + 1.0; invalid: expr. result is double • Error: Incompatible type for =. Explicit cast needed to convert double to int.

  24. Type casting • Casting: the most general form of conversion in Java. A cast is a Java operator specified by a type in parentheses, that is applied to the value of an expression. Type casting syntax: Form:(type) value Example: double cost; int dollars; dollars = (int) cost; Interpretation: The cast in the example creates an int value by converting cost to an integer (which truncates any fractional part). The content of cost remains unchanged. • More type casting examples: int count; count = (int) 3.6; int m = 7; int n = 2; double x; x = (double) m / n; int m = 7; int n = 2; double x; x = (double) (m /n); the cast operator creates an int value (i.e. 3), which is assigned to count • the cast operator creates a double value (i.e., 7.0) • n is converted to a double by arithmetic promotion • division produces the result 3.5, which is assigned to x • the integer division 7 / 2 gives the result 3 • the cast operator creates a double value (i.e., 3.0), which is assigned to x

  25. Rules for Evaluating Expressions • Parentheses rule: Evaluate expressions in parentheses separately. Evaluate nested parens. from the inside out. • Operator precedence rule: Operators in the same expression are evaluated in the order determined by their precedence (from the highest to the lowest). Operator Precedence • Left associative rule:Operators in the same expression and at the same precedence level are evaluated in left-to-right order. method callhighest precedence - (unary minus) new, type cast *, /, % +, - (binary) =lowest precedence

  26. Evaluation of z – (a + b / 2) * w / y z - (a + b / 2) * w / y Operator, reason evaluated --/--- /, parens. and precedence ---+------- +, parens. -------------*-- *, precedence, left assoc. ------------------/-- /, precedence -- - -------------------- -

  27. Mathematical Formulas in Java • a = bc not valid Java syntax • insert * Operator a = b * c; • m = y - b x - a • insert ( ) and / m = (y - b) / (x - a);

  28. Class TwoNumbers public class TwoNumbers { public static void main(String[] args) { double num1 = 8; double num2 = 6; System.out.println("First number is " + num1); System.out.println("Second number is " + num2); System.out.println("Sum is " + (num1 + num2)); System.out.println("Difference is " + (num1 - num2)); System.out.println("Product is " + (num1 * num2)); System.out.println("Quotient is " + (num1 / num2)); } }

  29. Sample run of class TwoNumbers

  30. 2.4 String class • A class (data type) that can be used to store and manipulate sequences of characters. • Use the String class to process text data instead of the more limited char data type which stores only single characters. • String variables reference objects that contain sequences of characters.

  31. Declaring String Variables • The declaration statements String name; String flower; declare two variables, name and flower, that can reference String objects. • Currently, no String objects exist. The values of name and flower are both null, which means they do not reference an object.

  32. New operator creates objects • The statements name = new String("Dustin"); flower = new String("Rose"); create two String objects using the new operator. The first String object contains the letters Dustin, and it is referenced by variable name; the second String object contains the letters Rose, and it is referenced by variable flower. • The process of creating an object using the new operator is called instantiation. • An object is an instance of a class or a class instance

  33. Constructor • The statement name = new String("Dustin"); calls a constructor which is a special method that has the same name as the class. • The constructor method stores the initial data in the object. The constructor argumentprovides information that the constructor needs to set up the object. • The argument is the string literal "Dustin" and it specifies the sequence of characters to be stored in the new object.

  34. Syntax for Class Instantiation • Form: variableName = new className(arguments); • Example: flower = new String("rose"); • Interpretation: An object of class className, is created which will be referenced by variableName. The data type of variableName must be type className. The constructor className stores the data specified by the arguments in the new object.

  35. Combining Variable Declaration and Object Creation • The statements String name = new String("Dustin"); String flower = new String("Rose"); create two string objects referenced by name and flower. • The data in quotes is stored in these objects

  36. Special Properties of Strings • The characters stored in a String object cannot be changed. For most classes, you can change the data stored in an object. • You can create a new String object just by writing the sequence of characters it contains as a literal (value). String name = "Robin"; String flower = "Rose"; • We will use String literals to designate new String objects rather than explicitly calling the String constructor. However, you must use constructors to create objects of other class types.

  37. String Operator + and String Assignment • the operator + means concatenate or join and is called the concatenation operator. The expression name + " " + flower creates a new String object with the characters contained in its three String operands. For the declarations in the previous slide, the new String object contains the characters Robin Rose. • The statement String fullName = flower + " " + name; declares String variable fullName which references the String object with characters Rose Robin.

  38. + mean concatenate if one or both of its operands is a string • Assume x is 5 and y is 7. The expression "The sum of x and y is " + x + y the left operator + (concatenate) forms a String object with the characters The sum of x and y is 5. The right operator + also means concatenate, so we get a String object that contains the characters The sum of x and y is 57 . • In the expression "The sum of x and y is " + (x + y) the right operator + (add) is first (12) and the expression result is a String object with: The sum of x and y is 12 . concatenate concatenate concatenate add

  39. String methods length(), charAt(), and substring() Method call Description "This string".length() Finds the length of string "This string". Result is 11. "This string".charAt(6) Gets the character in string "This string" at position 6, where first character is at position 0. Result is 't'. "This string".substring(5) Gets the part of string "This string" starting at position 5 through the end of the string. Result is "string". "This string".substring(5, 7) Gets the part of string "This string" starting at position 5 up to, but excluding, position 7. Result is "st".

  40. String method indexOf() Method call Description "This string".indexOf("is") Determines the position of the first occurrence of "is" in "This string". Result is 2. "This string".indexOf("it") Determines the position of the first occurrence of "it" in "This string". Result is -1 because "it" is not found. "This string".indexOf("i", 5) Determines the position of the first occurrence of "i" in "This string" starting the search at position 5. Result is -8.

  41. 2.5 input/output • Swing is a package (collection of classes) that facilitates user interaction through GUIs and dialog windows. • Class JOptionPane of Swing provides methods for input/output using dialog windows. • Place the statement import javax.swing.*; at the beginning of a source file to use the swing package.

  42. Import Statement • Form: import package; • Example: import javax.swing.*; import javax.swing.JOptionPane; • Interpretation: The import statement makes the class or classes in the specified package accessible to the classes that are defined in the current source file. The symbol * is a wildcard. It indicates that all classes in a directory or folder can be accessed, not just a particular one.

  43. Reading a string data item • The method call JOptionPane.showInputDialog( "Enter your name") pops up a dialog window. The method returns a reference to a String object that contains the characters typed in the text field (currently blank). • The statement String name = JOptionPane.showInputDialog( "Enter your name"); causes variable name to reference this String object.

  44. Reading type int data • The statement pair String str1 = JOptionPane.showInputDialog("Enter your age"); int age = Integer.parseInt(str2); stores an integer in age. The character(s) typed in by the user are stored in a String object referenced by str1. • The method call Integer.parseInt(str1) converts this string to a type int value which is stored in age. If the conversion cannot be done, an error message will appear in the console window and your program will stop execution. Method parseInt() is a class method defined in class Integer.

  45. Reading type double data • The statement pair String str2 = JOptionPane.showInputDialog("Enter your salary"); double salary = Double.parseDouble(str2); stores a real number in salary. Method parseDouble() is a class method defined in class Double and converts a string to a type double value.

  46. Reading character data • The statement pair String str3 = JOptionPane.showInputDialog( "Enter a single letter"); char initial = str3.charAt(0); stores a single data character in variable initial (type char). The method call str1.charAt(0) returns the first character read into string str3 which is then stored in variable initial.

  47. Using console window for output • The method calls System.out.print("First number is " + num1); System.out.println(“Second number is " + num2); display the value of num1 and num2 on the same line in the Java console window: First number is 8, second number is 10 num1 num2

  48. UsingshowMessageDialog() JOptionPane.showMessageDialog(null, "num1 is " + num1); String message = "num1 is " + num1 + “\nnum2 is " + num2; message is a String object containing the characters num1 is 8 \nnum2 is 6. JOptionPane.showMessageDialog(null, message);

  49. Java Keywords

  50. Identifiers • The other words in a statement are identifiers. A word that compiler recognizes as the name of datum (data field or variable).

More Related