Download presentation
Presentation is loading. Please wait.
1
COMP 14 Introduction to Programming
Adrian Ilie - COMP 14 - Summer 2005 COMP 14 Introduction to Programming Adrian Ilie Summer Session II, 2005 MTWRF 9:45-11:15 am Sitterson Hall 011
2
Adrian Ilie - COMP 14 - Summer 2005
About COMP 14 What made you register for Comp 14? Learn how to develop algorithms Learn the basic components of computer programming can be applied to any programming language (Java, C++, etc.)
3
Adrian Ilie - COMP 14 - Summer 2005
About COMP 14 Is COMP 14 right for you? Requirements / prerequisites no programming knowledge assumed
4
Adrian Ilie - COMP 14 - Summer 2005
About Me UNC graduate student 5th year Ph.D. student M.S. Computer Science from UNC Undergrad: Academy of Economic Studies, Bucharest, Romania Research interests: Computer Graphics, Computer Vision, camera allocation
5
Adrian Ilie - COMP 14 - Summer 2005
Course Web Page Schedule Lectures Documents Assignments Please visit the course page regularly!!
6
Adrian Ilie - COMP 14 - Summer 2005
Schedule Lectures MTWRF, 9:45-11:15 am, SN 011 Office Hours MTWR, 2-3 pm, SN 237
7
Adrian Ilie - COMP 14 - Summer 2005
Textbook Required Java Programming: From Problem Analysis to Program Design D. Malik, P. Nair ISBN: Optional Java Programming: Lab Manual Judy Scholl ISBN:
8
Adrian Ilie - COMP 14 - Summer 2005
Grades Assignments (7) 45% Quizzes (3) 10% Midterm 15% Final/Project 25% Class participation 5%
9
Adrian Ilie - COMP 14 - Summer 2005
Assignments Assignments are posted on the course page (check often), and due at 11:59pm on the due date turn in by or in class Homework assignments from textbook practice for exams Programming assignments budget hours per program design, code, debugging start early!
10
Adrian Ilie - COMP 14 - Summer 2005
Exams Midterm to take a make-up midterm, you must notify me in advance or have a doctor's excuse Final to take the exam at a different time, you must get permission from your Dean and bring me the blue slip you get from the Dean
11
Adrian Ilie - COMP 14 - Summer 2005
Collaborating You can talk to each other about the lecture topics talk about assignment requirements You should do your own assignments -- design and code You should not talk to each other about assignment solutions share code -- it is easy to detect Pledge form
12
Adrian Ilie - COMP 14 - Summer 2005
Software jGRASP Java Development Environment on public lab machines Start / All Programs / UNC Courseware / COMP 14 / jGRASP you can install on your machine see course home page We’ll do a tour later...
13
Adrian Ilie - COMP 14 - Summer 2005
Computer Labs UNC ITS labs: Davis Library Health Sciences Library Hinton James Residence Hall Law School Library R. B. House Undergraduate Library School of Public Health Student Union Venable Hall Schedules: Locations:
14
Adrian Ilie - COMP 14 - Summer 2005
COMP 14 Map best way from Sitterson to Venable lab is to go around Carroll hall, go down the stairs, take the first entrance on your right, and go all the way up the stairs.
15
Adrian Ilie - COMP 14 - Summer 2005
Working in the Lab Before you open jGRASP and start coding: read the assignment think about what the assignment is asking for review lectures and examples on the topic write (yes, on paper) your plan for completing the assignment (i.e., your algorithm) Talk to me if you’re having trouble at this point
16
Campus File System Andrew File System (AFS)
Adrian Ilie - COMP 14 - Summer 2005 Campus File System Andrew File System (AFS) Disk space associated with your Onyen automatically backed up by UNC AFS in the lab automatically appears as drive H: when you log in On your personal machine you can install the AFS Client won’t see drive H: unless you’re connected to the network (i.e., can access the Internet) More information see AFS guidelines on Help section of web page.
17
Adrian Ilie - COMP 14 - Summer 2005
Backup Your Work! Backup your work! You will lose something at some point you might have to learn the hard way Use your AFS space use of AFS space is not required, but is recommended
18
Adrian Ilie - COMP 14 - Summer 2005
Help! For help on general computer problems, including getting AFS enabled on your laptop or at home Also, for free software 962-HELP
19
Adrian Ilie - COMP 14 - Summer 2005
jGRASP Tour
20
Adrian Ilie - COMP 14 - Summer 2005
Homework 1 Some personal info Getting started with jGRASP Due tomorrow at midnight
21
Adrian Ilie - COMP 14 - Summer 2005
Next Class What is Computer Science? Introduction to Programming Reading Assignment: Chapter 1 Homework 1 is due tomorrow
22
COMP 14 Introduction to Programming
Adrian Ilie June 24, 2005 Hand out syllabus if necessary Intro myself again Go through class roll.
23
…from Last Time Homework 1 due at midnight
Fill in form with personal info Getting started with jGRASP Compile and Run test programs Any problems? Disable test for new versions
24
Today (ch. 1) Parts of the computer Binary numbers
hardware vs. software CPU and memory Binary numbers What is an algorithm? Once we know these 3 elements we can actually start coding our own programs.
25
Reading Check-Up hardware ________- computer components including the CPU, main memory, I/O devices, and secondary storage ________ - the brain of the computer, containing the CU, PC, IR, ALU, and ACC ________ - computer instructions to solve a problem The digits 0 and 1 are called _________ or the shortened term ________ CPU program Digits that can only take the values 0 and 1. binary digits bits
26
An Overview of the History of Computers
1950s: Very large devices available to a select few. 1960s: Large corporations owned computers. 1970s: Computers got smaller and cheaper. 1990s: Computers got cheaper and faster and were found in most homes.
27
Hardware vs. Software Hardware Software
A computer is made up of hardware and software Hardware Software CPU ex: 2 GHz Pentium IV input/output keyboard monitor network card main memory ex: 256 MB RAM secondary memory ex: 20 GB hard drive operating systems Windows XP Mac OS X applications games Microsoft Word Internet Explorer
28
Hardware Organization
CPU memory motherboard hard drive
29
Central Processing Unit
Control Unit (CU) "the brain" of the CPU Program Counter (PC) points to the next instruction to be executed Instruction Register (IR) holds the currently executing instruction Arithmetic Logic Unit (ALU) carries out all arithmetic and logical ops Accumulator (ACC) holds the results of the operations performed by the ALU CU fetch and decode instructions control the flow of info between CPU and main memory control the operation of the other CPU components
30
Main Memory Ordered sequence of cells AKA Random Access Memory (RAM)
Directly connected to the CPU All programs must be brought into main memory before execution When power is turned off, everything in main memory is lost
31
Main Memory With 100 Cells Each memory cell has a numeric address, which uniquely identifies it
32
CPU and Main Memory All programs must be brought into main memory before execution Chip that executes program instructions (processor) Primary storage area for programs and data that are in active use (RAM)
33
Secondary Storage Provides permanent storage for information
Retains information even when power is off Examples of secondary storage: Hard Disks Floppy Disks ZIP Disks CD-ROMs Tapes
34
Secondary Storage Secondary memory devices provide long-term storage
Information is moved between main memory and secondary memory as needed
35
Input Devices Definition: devices that feed data and computer programs into computers Examples: Keyboard Mouse Secondary Storage
36
Output Devices Definition: devices that the computer uses to display results Examples: Printer Monitor Secondary Storage
37
Input/Output Devices I/O devices facilitate user interaction
38
Hardware Components
39
Opening MS Word Use the mouse to select MS Word
The CPU requests the MS Word application MS Word is loaded from the hard drive to main memory The CPU reads instructions from main memory and executes them one at a time MS Word is displayed on your monitor
40
Questions ____________- points to the next instruction to be executed
____- a unique location in memory ____________- stores information permanently Instructions executed by the CPU must be first loaded to ________ program counter (PC) address secondary storage main memory
41
Software Categories Operating System Application
controls all machine activities provides the user interface to the computer first program to load when a computer is turned on manages computer resources, such as the CPU, memory, and hard drive examples: Windows XP, Linux, Mac OS X Application generic term for any other kind of software examples: word processors, missile control systems, games
42
Operating System (OS) OS monitors overall activity of the computer and provides services Written using programming language Example services: memory management input/output storage management
43
Application Programs Written using programming languages
Perform a specific task Run by the OS Example programs: Word Processors Spreadsheets Games
44
Questions Classify the following pieces of software as operating system or application: Microsoft Windows 2000 Microsoft PowerPoint Linux Your COMP 14 programs OS app OS app
45
It’s All About Data Software is data
numbers, characters instructions, programs Hardware stores and processes data read, write add, subtract, multiply, divide
46
Analog vs. Digital Two basic ways to store and manage data Digital
continuous wave forms ex: sound, music on an audio tape Digital the information is broken down into pieces, and each piece is represented separately is ultimately represented as series of 0s and 1s for low voltage and high voltage can be copied exactly ex: music on a compact disc Two basic ways to store and manage data Digital electrical signal digital is used inside the computer at its lowest-level, the computer only understands 0 and 1
47
Representing Text Digitally
All information in a computer is digitized, broken down and represented as numbers. H i , H e a t h e r . Corresponding upper and lower case letters are separate characters.
48
Language of a Computer Machine language: the most basic language of a computer A sequence of 0s and 1s binary digit, or bit sequence of 8 bits is called a byte Every computer directly understands its own machine language why can't Windows programs run on Apple computers? Once we digitize something, we have to convert those numbers to binary (the computer's language)
49
Bit Permutations 1 bit 1 2 bits 00 01 10 11 3 bits 000 001 010 011 100
1 2 bits 00 01 10 11 3 bits 000 001 010 011 100 101 110 111 4 bits 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Each additional bit doubles the number of possible permutations
50
Bit Permutations Each permutation can represent a particular item
There are 2N permutations of N bits N bits are needed to represent 2N unique items 1 bit ? 2 bits ? 3 bits ? 4 bits ? 5 bits ? How many items can be represented by 21 = 2 items 22 = 4 items 23 = 8 items 24 = 16 items 25 = 32 items
51
Binary Numbers N bits to represent 2N values
N bits represent values 0 to 2N-1 Example: 5 bits 32 unique values (0-31) = 010 = 3110 = 31
52
Converting Decimal to Binary
Let’s convert 114 to binary Repeatedly divide by 2 and write down the remainder: 114/2=57 remainder 0 57/2=28 remainder 1 28/2=14 remainder 0 14/2=7 remainder 0 7/2=3 remainder 1 3/2=1 remainder 1 1/2=0 remainder 1 Write the remainders in reverse order: =11410 Proof – rewrite and add the equations above: 114=(((((((1*2)+1)*2+1)*2+0)*2+0)*2+1)*2+0)= =1*26+1*25+1*24+0*23+0*22+1*21+0*20
53
Questions: Binary Numbers
What’s the maximum value a 6-bit number can represent? What’s the decimal representation of ? What’s the binary representation of 35? 26-1=63 25*1+24*1+23*1+22*0+21*1+20*0=58 5 minutes to work on these. Then show the calculator in the computer. 3510=
54
Storage Capacity Every memory device has a storage capacity, indicating the number of bytes (8 bits) it can hold Various units: Unit Symbol Number of Bytes kilobyte megabyte gigabyte terabyte KB 210 = 1024 MB 220 (over 1 million) GB 230 (over 1 billion) TB 240 (over 1 trillion)
55
Machine Language Early computers programmed in machine language (only 0s and 1s) Assembly languages were developed to make programmer’s job easier Assembler: translates assembly language instructions into machine language
56
Assembly and Machine Language
57
Programming Languages
High-level languages make programming easier Closer to spoken languages Examples: Basic FORTRAN COBOL C/C++ Java
58
Java and Machine Language
To run a Java program: Java instructions need to be translated into an intermediate language called bytecode. The bytecode is interpreted into a particular machine language.
59
Compiler Compiler: A program that translates a program written in a high-level language into the equivalent machine language. (In the case of Java, this machine language is the bytecode.) Java Virtual Machine (JVM): A hypothetical computer developed to make Java programs machine independent.
60
A Java Program public class ASimpleJavaProgram {
public static void main(String[] args) System.out.println("My first Java program."); System.out.println("The sum of 2 and 3 = " + 5); System.out.println("7 + 8 = " + (7 + 8)); } Sample Run: My first Java program. The sum of 2 and 3 = 5 7 + 8 = 15
61
Processing a Java Program
Program: written in Java using the Editor and compiled to Bytecode using the Compiler. Loader: transfers the compiled code (bytecode) into main memory and loads the necessary Libraries. Interpreter: reads and translates each bytecode instruction into machine language and then executes it.
62
Problem Solving The purpose of writing a program is to solve a problem
The general steps in problem solving are: understand the problem dissect the problem into manageable pieces design a solution consider alternatives to the solution and refine it implement the solution test the solution and fix any problems that exist
63
Algorithm Sequence of instructions used to carry out a task or solve a problem May be written in either English or pseudocode outline of a program that could be translated into actual code May need refinement as you work Always write out your algorithm before you begin programming
64
Problem-Analysis-Coding-Execution
most important step without computer with computer
65
Algorithm Design Example
Problem: Convert change in cents to number of half-dollars, quarters, dimes, nickels, and pennies to be returned. Example: given 646 cents number of half-dollars: divide 646 by 50 quotient is 12 (number of half-dollars) remainder is 46 (change left over) number of quarters: divide 46 by 25 quotient is 1 (number of quarters) remainder is 21 (change left over) number of dimes, nickels, pennies result: 12 half-dollars, 1 quarter, 2 dimes, 0 nickels, 1 penny
66
Resulting Algorithm Get the change in cents
Find the number of half-dollars Calculate the remaining change Find the number of quarters Find the number of dimes Find the number of nickels The remaining change is the number of pennies.
67
Exercise Execution of c=2*a+b in a computer
68
To do Read ch. 2 Exercise 10 in ch. 1 (algorithm design)
69
What’s Ahead... Java Basics Homework 1 due tonight
Homework 2 assigned Monday Quiz Tuesday: computers and Java basics
70
COMP 14 Introduction to Programming
Michele Weigle - COMP 14 - Spring 2004 COMP 14 Introduction to Programming Adrian Ilie June 27, 2005
71
Michele Weigle - COMP 14 - Spring 2004
Review Exercise Execution of c=2*a+b in a computer: Take the value of a Multiply it by 2 Take the value of b Add b to the previous result Put final result into c
72
Michele Weigle - COMP 14 - Spring 2004
Today in COMP 14 Java special symbols identifiers data types operators expressions strings
73
Michele Weigle - COMP 14 - Spring 2004
Reading Check-Up syntax The ________ rules of a language determine which instructions are valid. True or False? Hello! is an example of a legal Java identifier. _______ If an operator has an integer and a floating-point operand, the result of the operation is a ___________ number. The expression (int) (9.2) evaluates to ___. False floating-point 9
74
Michele Weigle - COMP 14 - Spring 2004
Introduction Computer program: a sequence of statements whose objective is to accomplish a task Programming: process of planning and creating a program Programming language: a set of rules, symbols, and special words
75
Michele Weigle - COMP 14 - Spring 2004
Sample Java Program public class Hello { public static void main (String[] args) System.out.println ("Hi There!"); } Upon execution, this program would display Hi There!
76
Programming Languages
Michele Weigle - COMP 14 - Spring 2004 Programming Languages Programming languages have rules of grammar just as English does syntax rules - which statements are legal and which are not semantic rules - determine the meaning of the instructions token - smallest individual unit of a program special symbols word symbols identifiers
77
Michele Weigle - COMP 14 - Spring 2004
Special Symbols + - * / . ; ? , <= != == >= the 3rd row contains two characters that together (with no space between them) are considered to be a single symbol
78
Word Symbols aka reserved words, or keywords
Michele Weigle - COMP 14 - Spring 2004 Word Symbols aka reserved words, or keywords int float double char void public static throws return reserved words are always all lowercase each word symbol is considered to be a single symbol cannot be used for anything other than their intended purpose in a program shown in blue typewriter font in textbook full table in Appendix A
79
Michele Weigle - COMP 14 - Spring 2004
Identifiers Names of things (variables, constants, methods) in your programs Can be composed of any combination of letters, digits, underscore (_), and dollar sign ($) Cannot begin with a digit May be any length Java is case-sensitive Total, total, and TOTAL are different identifiers
80
Michele Weigle - COMP 14 - Spring 2004
Illegal Identifiers
81
Michele Weigle - COMP 14 - Spring 2004
Questions Classify the following as legal or illegal identifiers: My First Program ____ my1stProgram ____ 1stProgram ____ $money ____ an_identifier ____ Jane'sProgram ____ illegal legal illegal legal legal illegal
82
Primitive Data Types What’s A Data Type?
Michele Weigle - COMP 14 - Spring 2004 Primitive Data Types What’s A Data Type? A set of values and the operations that can be performed on those values Primitive data are fundamental values such as numbers and characters Operations are performed on primitive types using built-in operators certain types of operations can only be performed on certain types of data example: you can multiply numbers, but not words
83
Michele Weigle - COMP 14 - Spring 2004
Primitive Data Types 8 primitive data types in Java 4 represent integers byte, short, int, long 2 represent floating point numbers float, double 1 represents characters char 1 represents boolean values boolean
84
Primitive Data Types Numeric Types
Michele Weigle - COMP 14 - Spring 2004 Primitive Data Types Numeric Types The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 +/- 3.4 x 1038 with 7 significant digits +/- 1.7 x with 15 significant digits Max Value 127 32,767 2,147,483,647 > 9 x 1018 float - at most 6 or 7 places after the decimal point double - at most 15 places after the decimal point some compilers will complain if you use float, so we will use double throughout this class
85
Michele Weigle - COMP 14 - Spring 2004
Integers Examples: -6728, -67, 0, 78, 36782 Positive integers do not have a '+' sign in front of them (but they can) No commas are used in an integer commas in Java are used to separate items in a list
86
Primitive Data Types Characters
Michele Weigle - COMP 14 - Spring 2004 Primitive Data Types Characters A char stores a single character from the Unicode character set an ordered list of characters, and each character corresponds to a unique number uses 16 bits per character, allowing for 65,536 unique characters Character literals are delimited by single quotes: 'a' 'X' '7' ' ' '$' ',' '\n' ordered list of characters for example, the value 65 represents uppercase 'A' 66 represents uppercase 'B' the full list of Unicode / ASCII is in Appendix C of the textbook newline character (we'll discuss later)
87
Primitive Data Types Booleans
Michele Weigle - COMP 14 - Spring 2004 Primitive Data Types Booleans Only two valid values true or false uses 1 bit for storage Represent any situation that has 2 states on - off true - false true and false are reserved words We'll see a lot more of booleans and boolean expressions later on in the semester
88
Arithmetic Expressions
Michele Weigle - COMP 14 - Spring 2004 Arithmetic Expressions Expression - a combination of one or more operands and their operators Arithmetic expressions compute numeric results and make use of the arithmetic operators: If either or both operands associated with an arithmetic operator are floating point, the result is a floating point Addition + Subtraction - Multiplication * Division / Remainder %
89
Division and Remainder
Michele Weigle - COMP 14 - Spring 2004 Division and Remainder If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) The remainder, or modulus, operator (%) returns the remainder after dividing the second operand into the first (only works with integer types) 14 / 3 equals? 4 8 / 12 equals? 14 % 3 equals? 8 2 8 % 12 equals?
90
Unary vs. Binary Operators
Michele Weigle - COMP 14 - Spring 2004 Unary vs. Binary Operators Unary operators has only one operand example: - (negative, not subtraction) -5 Binary operators has two operands example: - (subtraction) 5 - 3
91
Michele Weigle - COMP 14 - Spring 2004
Operator Precedence Determines the order in which operators are evaluated: multiplication, division, and remainder addition, subtraction, and string concatenation arithmetic operators with the same precedence are evaluated from left to right Parentheses can be used to force the evaluation order (just like in math)
92
Michele Weigle - COMP 14 - Spring 2004
Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1
93
Michele Weigle - COMP 14 - Spring 2004
Integral Expressions All operands are integers Result is an integer Examples: 2 + 3 * 5 3 + x – y / 7 x + 2 * (y – z) + 18 in these expressions, x, y, and z are some unknown numbers.
94
Floating-point Expressions
Michele Weigle - COMP 14 - Spring 2004 Floating-point Expressions All operands are floating-point numbers Result is a floating-point Examples: 12.8 * 17.5 – 34.50 x * y 7.0 / 3.5 in these expressions, x and y are some unknown numbers.
95
Michele Weigle - COMP 14 - Spring 2004
Mixed Expressions Operands of different types Examples: ________ 6 / ________________ Integer operands yield an integer result Floating-point operands yield a floating-point result If both types of operands are present, the result is a floating-point number implicit type coercion Precedence rules are followed = if you have both integer and floating -point operands, the integer will be converted to a floating-point number and the operation will take place -- the result will be floating-point
96
Type Conversion (Casting)
Michele Weigle - COMP 14 - Spring 2004 Type Conversion (Casting) Used to avoid implicit type coercion Syntax (dataTypeName) expression Expression evaluated first, then type converted to dataTypeName Examples: (int) ( ) = 14 (int) (7.9) + (int)(6.7) = 13 casting a floating-point number to an integer truncates everything after the decimal point (int) 14.6 7 + 6 the textbook has very nice examples of mixed expressions and casting on pgs make sure you take a look at them and understand the answers
97
Questions Evaluate These Expressions
Michele Weigle - COMP 14 - Spring 2004 Questions Evaluate These Expressions 9 % 6 3 (5 + 4) % 6 (5 + 6) % 3.5 (double) (13) / 2 (double) (13 / 2) 11 % 3.5 not possible 13.0 / 2 6.5 (double) (6) 6.0
98
Michele Weigle - COMP 14 - Spring 2004
The class String String sequence of zero or more characters enclosed in double quotation marks null or empty strings have no characters numeric strings consist of integers or decimal numbers length is the number of characters in a string The class String is used to manipulate strings Examples: "Hello World" "1234" "45.67" "" note the null, or empty, string
99
Michele Weigle - COMP 14 - Spring 2004
Strings Every character has a position in the string (starting with 0) "Hello World" The length of the string is the number of characters in it what's the length of "Hello World"? 11 (count the space)
100
Parsing Numeric Strings
Michele Weigle - COMP 14 - Spring 2004 Parsing Numeric Strings In Java, input from the user comes in the form of a string we need to know how to get the number values out of the string Numeric String a string with only integers or decimal numbers "6723", "-823", "345.76"
101
Parsing Numeric Strings
Michele Weigle - COMP 14 - Spring 2004 Parsing Numeric Strings String to int Integer.parseInt(strExpression) Integer.parseInt("6723") 6723 String to float Float.parseFloat(strExpression) Float.parseFloat("345.76") String to double Double.parseDouble(strExpression) Double.parseDouble(" ") the capital letters in Integer, Float, and Double are important -- Java is case-sensitive!
102
Michele Weigle - COMP 14 - Spring 2004
Summary Identifiers can be composed of any combination of letters, digits, underscore (_), and dollar sign ($) cannot begin with a digit Java is case-sensitive Data Types main integer type: int main floating-point type: double others: char, boolean
103
Michele Weigle - COMP 14 - Spring 2004
Summary Arithmetic Operators: If one of the operands is floating-point, the result is a floating-point Can only use % with two integer operands Casting (int) (54.9) - truncates the floating-point number (double) (23) - adds a .0 to the integer addition + subtraction - multiplication * division / remainder (mod) %
104
Michele Weigle - COMP 14 - Spring 2004
To do Homework 2 assigned today Algorithm design Theory questions First program (after tomorrow’s class) Read ch. 2 (pp. 37-end)
105
Michele Weigle - COMP 14 - Spring 2004
Tomorrow First QUIZ! Writing a whole program
106
COMP 14 Introduction to Programming
Adrian Ilie June 28, 2005
107
Today Variables and expressions Input/Output Writing a whole program
108
Variables Associated with data We need to define:
Input data Output data Intermediate data We need to define: Data type Identifier Values will be assigned in expressions Start by learning how to declare variables Variables are associated with data
109
Variables - Steps Identify all data from the algorithm
Determine data types (based on the range and nature of the values) Find meaningful names Example: Ch. 1, Exercise 10. Compute average score.
110
Declaration of Variables
dataType identifier; Must be declared before it can be used Can be (but doesn't have to be) initialized when declared Identifier should start in lowercase, indicate separate words with uppercase (good style) Example: number of students in class int numStudents; Multiple variables (of the same data type) can be declared on a single line int numStudents, numGrades, total;
111
variable = expresssion;
Assignment variable = expresssion; Assignment Operator (=) expression can be a value (3) or a mathematical expression (2 + 1) The expression must evaluate to the same data type as the variable was declared
112
Assignment The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = sum / 4 + MAX * lowest; 4 1 3 2 Then the result is stored in the variable on the left hand side
113
Assignment The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count count = count + 1; Then the result is stored back into count (overwriting the original value)
114
Example (average score)
Write assignments and expressions Declaration of variables (good style) At the beginning Before being used
115
Named Constant Declared by using the reserved word final
static final dataType IDENTIFIER = value; Declared by using the reserved word final Always initialized when it is declared Identifier should be in ALL CAPS, separate words with underscore (_) (good style) Example: 1 inch is always 2.54 centimeters final double CM_PER_INCH = 2.54; static is optional (we'll talk about when you have to use it next week) initialized -- given some initial value the compiler will give an error if you try to change the value of a constant after it's been declared and initialized
116
Questions What is stored in the memory location referred to by the identifier num after each of the following statements is executed in order? int num; ______ num = 3; ______ num = ; ______ num = num * 2; ______ num = ; ______ unknown 3 7 14 error would give an error since would not result in an int
117
Questions Which of the following are valid Java assignment statements? Assume that i, x, and percent have been declared as double variables and properly initialized. i = i + 5; ______ x + 2 = x; ______ x = 2.5 * x; ______ percent = 10%; ______ valid invalid valid invalid
118
Input Standard input Dialog windows (tomorrow) File (tomorrow)
We’re going to study 3 ways to input variables to the program.
119
Reading Keyboard Input
We can let the user assign values to variables through keyboard input In Java, input is accomplished using objects that represent streams of data A stream is an ordered sequence of bytes System.in is the standard input stream object (by default, the keyboard)
120
Reading Keyboard Input
The idea is that, with System.in, we have access to a stream of bytes coming from the keyboard. In other words, we have access to the keys pressed on the keyboard. But how do we actually get the values of the keys that are pressed?
121
Reading Keyboard Input
The input stream is made up of multiple objects: InputStreamReader charReader = new InputStreamReader (System.in); BufferedReader keyboard = new BufferedReader (charReader); OR, all in one statement: BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in)); 1 character at a time Whole line at once We can think of an object as a complex data type (not integer or character). We'll talk more about objects next week. Java gives us the code. We don't have to understand everything behind it right now -- we'll discuss it later. We just need to be able to use this code.
122
Reading Keyboard Input
The readLine method of the BufferedReader class reads an entire line of input as a String String line = keyboard.readLine(); For right now, think of a method as a set of instructions designed to accomplish a specific task. We'll talk more about methods next week.
123
Example (average score)
Input scores Input weights
124
String to Numbers String to int String to float String to double
Integer.parseInt(strExpression) Integer.parseInt("6723") 6723 String to float Float.parseFloat(strExpression) Float.parseFloat("345.76") String to double Double.parseDouble(strExpression) Double.parseDouble(" ") the capital letters in Integer, Float, and Double are important -- Java is case-sensitive!
125
Example (average score)
Convert scores to int Convert weights to double
126
Puts the cursor on the next line at the end
Output Standard output device is usually the monitor Access the monitor using the standard output object System.out Two methods to output a string: print println We've talked about how to get input from the user. Now, how do we print things out to the user? Puts the cursor on the next line at the end
127
Examples ‘num’ is converted to a string!!! System.out.println ("Hi");
System.out.println ("There"); Hi There System.out.print ("Hi"); System.out.println ("There"); HiThere int num = 5+3; System.out.println (num); 8 ‘num’ is converted to a string!!! int num = 5; System.out.println ("The sum is " + (num + 3)); The sum is 8
128
X String Concatenation A string cannot be split between two lines
String greeting = "How are you doing today"; Concatenation (+) - produces one string where the second string has been appended to the first string String greeting = “How are you doing” “ today?”; X How are you doing today? greeting
129
String Concatenation Operator + can be used to concatenate two strings or a string and a numeric value or character Precedence rules still apply Example: String str; int num1 = 12, num2 = 26; str = "The sum = " + num1 + num2; The sum = 1226 str
130
Example (average score)
Output result Formatting numeric strings
131
Writing a Whole Program
Class - used to group a set of related operations (methods), allows users to create their own data types Method - set of instructions designed to accomplish a specific task Package - collection of related classes Library - collection of packages
132
Class Libraries A collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment The System class and the String class are part of the Java standard class library The Java standard class library classes are not part of the Java language itself, but we rely on them heavily.
133
Packages The classes of the Java standard class library are organized into packages. Some of the packages in the standard class library are: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities XML document processing We’ll talk about how to use these next...
134
Using Packages We need to import some of the packages we want to use
java.io for BufferedReader import packageName; import java.io.*; imports all of the classes in the java.io package import java.io.BufferedReader; imports only the BufferedReader class from the java.io package
135
Using Predefined Classes and Methods
To use a method you must know: Name of class containing method (Math) Name of package containing class (java.lang) Name of method (round), its parameters (double a), what it returns (long), and function (rounds a to the nearest integer) See Appendix E for more Java predefined classes
136
Using Predefined Classes and Methods
Example method call: int num = (int) Math.round (4.6); (Dot) . Operator: used to access the method in the class
137
Creating a Java Program
Java application program - collection of one or more classes every application must have at least one class Class basic unit of a Java program collection of methods and data members Method - set of instructions designed to accomplish a specific task print, readLine
138
Programming in Java Java programming language
object-oriented approach to problem solving In the Java programming language: a program is made up of one or more classes a class contains one or more methods a method contains program statements
139
Creating a Java Program
All Java application programs must have a method called main there can be only one main method in any Java application program Most of the time, our programs will have only one class Name of source file must be ClassNameWithMain.java
140
Anatomy of a Java Program
Syntax of class Syntax of main method public class ClassName { classMembers } public static void main (String[] args) { statement1 ... statementn } throws clause
141
Throws Clause throws clause - exceptions thrown by the main method
exception - occurrence of an undesirable situation that can be detected during program execution can either be handled or thrown readLine throws the exception IOException We won't handle the exception, we'll just throw it
142
Throws If we're allowing user input to the program, the heading of the main method should look like: public static void main (String[] args) throws IOException
143
Import Statements Tell the compiler which packages are used in the program Import statements and program statements constitute the source code Source code saved in a file with the extension .java Source code file must have the same name as the class with the main method
144
The main method Heading Body public static void main (String[] args)
statements enclosed by { } declaration statements used to declare things such as variables executable statements perform calculations, manipulate data, create output, accept input, etc. public static void main (String[] args) throws IOException
145
Skeleton import statements if any public class ClassName {
declare named constants and/or stream objects public static void main (String[] args) throws IOException variable declarations executable statements }
146
static Heading of the main method has the reserved word static
Statements to declare named constants and input stream objects are outside the main method These must also be declared with the static reserved word We'll talk more about the static keyword on later classes
147
Style Syntax Use of semicolons, braces, commas
beware! a syntax error in one place might lead to syntax errors in several other places Use of semicolons, braces, commas all Java statements end with semicolon braces {} enclose the body of a method and set it off from other parts of the program (also have other uses) commas separate list items
148
Style Semantics Documentation
set of rules that gives meaning to a language beware! the compiler will not be able to tell you about semantic errors (example: missing parentheses in mathematical expression) Documentation comments naming rules use meaningful identifiers prompt lines let the user know what type of input is expected
149
Style and White Space White space
blanks, tabs, blank lines used to separate words and symbols extra space is ignored by computer blank line between variable declaration and rest of code Programs should be formatted to enhance readability, using consistent indentation
150
Comments Not used by the computer Used to help others understand code
only for human consumption Used to help others understand code explain and show steps in algorithm comments are essential! Should be well-written and clear Comment while coding Also called inline documentation
151
Java Comments // this is a one-line comment /* this is a multi-line
“comments out” the rest of the line after marker // /* this is a multi-line comment */ “comments out” everything between markers /* and */
152
To do Practice input. Ch. 2 (pp.45-54)
Practice output. Ch. 2 (pp.55-65) Ch. 2 examples: Convert Length Make Change Homework 2 due Thursday night. Read Ch. 3
153
COMP 14 Introduction to Programming
Adrian Ilie June 29, 2005
154
Yesterday Variables and expressions Input/output
Writing a whole program Any questions?
155
Today Classes and objects Graphical user interface (GUI)
File input/output Formatting input and output
156
Classes In the Java programming language:
a program is made up of one or more classes a class contains one or more methods a method contains program statements
157
Classes What is a class? Classes allow creation of new data types Data
Operations Classes allow creation of new data types public class Student { }
158
Classes Vs. Data Types Abstract Descriptors Concrete Entities Variable
Object
159
Inside a class Other classes Data types Methods (operations)
public class Student { private String name; private int age; public void ComputeGrade(); }
160
Primitive Variables int x = 45;
x is associated with a memory location. It stores the value 45 When the computer sees x, it knows which memory location to look up the value in Remember that a variable is just a name we give for a memory location. When we declare a variable of a primitive data type (int, double, char...), memory for that data type is reserved, and the address of the data is associated with the variable.
161
Reference Variables Integer num;
The memory location associated with num can store a memory address. The computer will read the address in num and look up an Integer object in that memory location Just like we can declare an int, we can declare an Integer variable. Note that we haven't yet created an object, we've just created a placeholder for the address for the object.
162
Creating Objects We use the new operator to create objects, called instantiation Integer num; num = new Integer(78); parameter The first line creates a reference variable. The second line creates the Integer object, initializes the Integer value, and stores the address where the object was created in num an object is an instance of a particular class
163
Changing the Reference Var
num = new Integer (50); The address of the newly-created object is stored in the already-created reference variable num How would you change the value in the Integer object from 78 to 50? The Integer class doesn't provide a method for changing the value. We could create a new Integer object that stored 50.
164
Garbage Collection What happened to the memory space that held the value 78? If no other reference variable points to that object, Java will "throw it away" This is just another way of looking at the previous figure. We say that the reference variable num "points to" the Integer object that contains the value 50.
165
information provided to
Using Objects System.out object represents a destination to which we can send output Example: println method System.out.println (”Hello World!”); object information provided to the method (parameters) method dot operator
166
Questions False new dot (.) True
True or False. A primitive variable is a variable that stores the address of a memory space. ______ The operator ____ is used to create a class object. In Java, the ________ operator is used to access members of a class. It separates the class (or object) name from the method name. True or False. Class objects are instances of that class. ______ False new dot (.) True
167
The class String String variables are reference variables
Given String name; Equivalent Statements: name = new String(“Van Helsing”); name = “Van Helsing”;
168
name = “Van Helsing”; Van Helsing Van Helsing Van Helsing
169
The class String The String object is an instance of class string
The value “Van Helsing” is instantiated The address of the value is stored in name The new operator is unnecessary when instantiating Java strings String methods are called using the dot operator
170
Common String Methods String(String str) char charAt(int index)
constructor creates and initializes the object char charAt(int index) returns char at the position specified by index (starts at 0) int indexOf(char ch) returns the index of the first occurrence of ch int compareTo(String str) returns negative if this string is less than str returns 0 if this string is the same as str returns positive if this string is greater than str All String class methods are in Appendix E (pgs )
171
Common String Methods boolean equals(String str) int length()
returns true if this string equals str int length() returns the length of the string String replace(char toBeReplaced, char replacedWith) returns the string in which every occurrence of toBeReplaced is replaced with replacedWith String toLowerCase() returns the string that is the the same as this string, but all lower case String toUpperCase() returns the string that is the same as this string, but all upper case
172
String Examples 11 n 7 van helsing
String str = “Van Helsing"; System.out.println (str.length()); System.out.println (str.charAt(2)); System.out.println (str.indexOf(‘s'); System.out.println (str.toLowerCase()); 11 n 7 van helsing The value in str does not change unless you assign something to it. Using the methods here, doesn't change the value of the string.
173
Using Dialog Boxes for I/O
Use a graphical user interface (GUI) class JOptionPane Contained in package javax.swing showInputDialog allows user to input a string from the keyboard showMessageDialog allows the programmer to display results Program must end with System.exit(0);
174
JOptionPane Methods showInputDialog showMessageDialog
str = JOptionPane.showInputDialog(strExpression); stores what the user enters into the String str showMessageDialog JOptionPane.showMessageDialog(parentComponent, strExpression, boxTitleString, messageType); str here could be any String that we have previously declared
175
showMessageDialog parentComponent StrExpression boxTitleString
parent of the dialog box we'll use null StrExpression what you want displayed in the box boxTitleString title of the dialog box messageType what icon will be displayed
176
messageType JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE
error icon JOptionPane.INFORMATION_MESSAGE information icon JOptionPane.PLAIN_MESSAGE no icon JOptionPane.QUESTION_MESSAGE question mark icon JOptionPane.WARNING_MESSAGE exclamation point icon
177
JOptionPane Example JOptionPane.showMessageDialog (null,
"Hello World!", "Greetings", JOptionPane.INFORMATION_MESSAGE);
178
UsingGUI.java example
179
Reading From Text Files
Similar to reading from the keyboard Create a BufferedReader object, but use a FileReader object instead of InputStreamReader Create BufferedReader object inside the main method instead of outside Substitute the name of the file for System.in When finished reading from the file, we need to close the file: BufferedReader close() method
180
Reading From Text Files
String file = "data.dat"; BufferedReader inFile = new BufferedReader (new FileReader (file)); String line = inFile.readLine(); inFile.close();
181
Exceptions FileNotFoundException IOException
if the file specified to open was not found IOException some other I/O exception public static void main (String[] args) throws FileNotFoundException, IOException
182
Writing To Text Files Similar to reading from text files
Use FileWriter and PrintWriter instead of FileReader and BufferedReader PrintWriter methods include print() and println(), just like those we used in System.out Like reading, we need to close the file when we're done PrintWriter close() method will overwrite the file that you're writing to
183
Writing To Text Files String file = "outfile.dat";
PrintWriter outFile = new PrintWriter (new FileWriter (file)); outFile.print ("Hi"); outFile.println(" There!"); outFile.close();
184
User Input BufferedReader Integer.parseInt How to handle?
reads everything as a string Integer.parseInt only handles one integer in the string How to handle? Enter 3 numbers:
185
The StringTokenizer Class
tokens elements that comprise a string tokenizing process of extracting these elements delimiters characters that separate one token from another StringTokenizer class defined in the java.util package used to separate a string into tokens
186
Tokens and Delimiters “The weekend is over" "Bart:Lisa:Homer:Marge"
delimiter: ' ' (space) tokens: “The’’ “weekend’’ “is’’ “over’’ "Bart:Lisa:Homer:Marge" delimiter: ':' tokens: "Bart" "Lisa" "Homer" "Marge"
187
The StringTokenizer Class
Default delimiters: space, tab, carriage return, new line Methods StringTokenizer (String str) StringTokenizer (String str, String delimits) String nextToken() boolean hasMoreTokens() int countTokens() Note that the first two are called constructors -- they have the same name as the class countTokens -- returns the number of tokens left in the String
188
Tokenize.java example separated by spaces separated by commas
don't put spaces in between comma and next token if you've only specified that the delimiter is a comma
189
Formatting the Output of Decimal Numbers
float: defaults to 6 decimal places double: defaults to 15 decimal places
190
class DecimalFormat Import package java.text
Create DecimalFormat object and initialize DecimalFormat fmt = new DecimalFormat (formatString); FormatString "0.00" - limit to 2 decimal places, use 0 if there's no item in that position "0.##" - limit to 2 decimal places, no trailing 0 Use method format rounds the number instead of truncating Result of using DecimalFormat is a String
191
Examples 56.38 56.38 0.35 0.35 0.30 0.3 DecimalFormat twoDecimal =
new DecimalFormat("0.00"); DecimalFormat fmt = new DecimalFormat("0.##"); System.out.println (twoDecimal.format(56.379)); _______ System.out.println (fmt.format(56.379)); _______ System.out.println (twoDecimal.format(.3451)); _______ System.out.println (fmt.format(.3451)); _______ System.out.println (twoDecimal.format(.3)); _______ System.out.println (fmt.format(.3)); _______ 56.38 56.38 0.35 0.35 0.30 0.3
192
To do Ch. 3 examples: Homework 2 due tomorrow.
Movie Ticket Sale Donation to Charity Student Grade Homework 2 due tomorrow. Homework 3 due next Tuesday. Read Ch. 4
193
COMP 14 Introduction to Programming
Adrian Ilie June 30, 2005
194
Today Control Structures Relational Operators Comparing Strings
Boolean Expressions If statements If-Else statements
195
Example: Sorting Cards
Some words used in the algorithm: when, until, if, otherwise, once… How can we express them in Java?
196
Control Structures Three methods of processing a program: In sequence
statements are executed one after another in order Branching altering the flow of program execution by making a selection or choice Looping altering the flow of program execution by repetition of statement(s) selection - program executes particular statements depending on some conditions repetition - program repeats particular statements a certain number of times depending on some condition
197
Flow of Execution
198
Examples of Conditionals
Note: the following are not actual Java statements 1) if (score is greater than or equal to 90) grade is A 2) if (hours worked are less than or equal to 40) wages = rate * hours otherwise wages = (rate * 40) * (rate * (hours - 40)) 3) if (temperature is greater than 70 degrees and it is not raining) recommended activity is golfing certain statements will only be executed if the condition evaluates to true if the condition evaluates to false, the statements will not be executed
199
Relational Operators Relational Operator
allows you to make comparisons in a program binary operator needs two operands Condition is represented by a logical (Boolean) expression expression that has a value of either true or false To make decisions, you need to be able to make comparisons
200
Relational Operators Less than < Greater than > Equal to ==
not assignment ‘=‘ Not equal to != Less than or equal to <= Greater than or equal to >=
201
Comparing Characters In Java, characters are ordered according to the Unicode / ASCII character set (pg. 855) ‘a’ comes before ‘b’ in the character set, so we can say ‘a’ < ‘b’ Order space character (' ') digits (‘0’, ‘1’, …) uppercase lowercase Application: sort alphabetically Makes it easy to alphabetize (just do compares)
202
Comparing Characters 'a' > 'A' '6' < 7 ' ' <= 's'
97 > true 54 < false 32 <= true lowercase letters appear later in the ASCII code than uppercase letters, so the value of 'a' is greater than the value of 'A' the character 6 is represented by 54 in the ASCII table, which is greater than 7 space comes before any of the letters in the ASCII table
203
Comparing Floating-Point
Be careful when using the equality (==) to compare floating point numbers Every bit in the representation must be equal computer can only store a certain number of digits after the decimal If the numbers are results of computation, it’s unlikely that two floating point numbers will be exactly equal
204
Comparing Floating-Point
3.0 / 7.0 2.0 / 7.0 (3.0 / 7.0) + (2.0 / 7.0) + (2.0 / 7.0) == 1 false If we did this math with exact arithmetic, this expression would be true
205
Comparing Strings Strings are compared on a character-by-character basis first character not in common determines how the strings compare ex: "Airplane" is less than "Airport" If two strings have different lengths, and one is a substring of the other, the shorter one is evaluated as less ex: "Air" is less than "Airplane"
206
Comparing Strings Don't use relational operators (==, <, >)
for Strings str1.compareTo (str2) Returns an integer value: < 0 if str1 is less than str2 0 if str1 is equal to str2 >0 if str1 is greater than str2 str1.equals (str2) Returns a boolean value of true or false method parameter
207
Questions Given String str = "Homer"; str.compareTo("Marge")
str.equals("homer") str.compareTo("Bart") negative value false positive value
208
Boolean Expressions Remember that booleans in Java are
true false A boolean expression is an expression that can be evaluated to either true or false Examples of boolean expressions: 2+2 is not equal to 5 a is equal to 0 10 is less than 5 Named for George Boole ( ), the founder of symbolic logic
209
Boolean Operators NOT ! (unary) AND && (binary) OR || (binary) true
!(2+2==5) AND && (binary) (2+2==5) && (1+1==2) OR || (binary) (2+2==5) || (1+1==2) true false true
210
NOT Operator
211
AND and OR Operators These are called truth tables -- helps you to figure out how complex expressions will be evaluated
212
Boolean Expressions Examples
Simple: 2+2 is not equal to != 5 10 is less than < 5 'A' is equal to 7 'A' == 7 Compound: a is equal to 3 and b is equal to 5 (a==3) && (b==5) x is not equal to 2 or y is less than 4 (x!=2) || (y<4) s is not equal to b and t is greater than or equal to 3 or t is less than 0 (s!=b) && (t>=3) || (t<0)
213
Short Circuited Operators
The processing of logical AND (&&) and logical OR (||) is “short-circuited” If the left operand is sufficient to determine the result, the right operand is not evaluated Be careful when counting on this type of processing count != 0 && (total/count > MAX)
214
Precedence of Operators
215
Boolean Expressions Logical expression that evaluates to true if the value of num is between 0 and 10 0 <= num <= 10 0 <= num && num <= 10 incorrect syntax correct syntax
216
Questions boolean ch < 'A' or ch > 'Z' compareTo
What type of primitive variable can the result of a logical expression be stored in? _______ Under what conditions would the expression ((ch >= 'A') && (ch <= 'Z')) evaluate to false? ______________________ What method do you use to compare two Strings? __________ Why is 'a' greater than 'A'? ______________________________________ boolean ch < 'A' or ch > 'Z' compareTo 'a' comes after 'A' in the ASCII character table
217
Questions false true true true int count = 0, sum = 54;
Given the following declarations, evaluate each Boolean expression: int count = 0, sum = 54; double x = 4.3, y = 1.2; boolean wrong = true; (wrong && sum > 60) ((x > 5) || !(sum == 55)) !((y > 1.0) && (x < 4)) ((count != 4) || (sum > 100) && wrong) false (true && false) true (false || !(false)) && is evaluated before || true !(true && false) true (true || false && true) (true || false)
218
Conditional Statements
Let us choose which statement will be executed next also called selection statements Java's conditional statements: the if statement the if-else statement the switch statement (tomorrow’s class) Conditional statements give us the power to make basic decisions about flow control
219
One-Way Selection Syntax: if (expression) statement
220
The if Statement if ( condition ) statement;
The condition must be a boolean expression. It must evaluate to either true or false. if is a Java reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.
221
The if Statement if (sum > MAX) delta = sum - MAX;
System.out.println ("The sum is " + sum); First, the condition is evaluated. The value of sum is either greater than the value of MAX, or it is not. If the condition is true, the assignment statement is executed. If it is not, the assignment statement is skipped. Either way, the call to println is executed next.
222
Block Statements Syntax: { statement1 statement2 . statementn }
We use curly braces to group a set of individual statements. This way we can have multiple statements execute based on a decision. If we don't use curly braces, only a single statement will be executed based on the result of a decision. Syntax: { statement1 statement2 . statementn }
223
The if Statement if (sum > MAX) delta = sum - MAX; A
System.out.println ("The sum is " + sum); A if (sum > MAX) { delta = sum - MAX; } System.out.println ("The sum is " + sum); B Code A and Code B do the exact same things. The braces point out a block of code. A block is a group of one or more statements delimited by a set of curly braces. Anywhere we say a statement is executed, a block could have been executed The braces in Code B allow us to add more than one statement that should execute if the condition is true. In these examples, Code C will execute only the println statement if the condition is true. Notice the indentation of the code remember that the computer ignores whitespace like tabs Use braces even when not required if (sum > MAX) { delta = sum - MAX; System.out.println ("The sum is " + sum); } C
224
Curly Braces int num = 87, max = 25; if (num >= max*2) System.out.println ("apple"); System.out.println ("orange"); System.out.println ("pear"); int num = 87, max = 25; if (num >= max*2) { System.out.println ("apple"); } System.out.println ("orange"); System.out.println ("pear"); These two code boxes produce the same output. Even though the indentation is incorrect, it's easier to tell what will be output when braces are used.
225
ToLower.java Example
226
Watch out! if (score >= 90); grade = "A";
No matter the result of the condition, grade will be assigned "A". The semicolon after the if statement is a semantic error.
227
Two-Way Selection
228
The if-else Statement if ( condition ) statement1; else statement2;
If the condition is true, statement1 is executed; if the condition is false, statement2 is executed An else clause can be added to an if statement to make an if-else statement Remember that if we used curly braces, we could replace statement1 and statement 2 with block1 and block2 One or the other will be executed, but not both
229
The if-else Statement if (height <= MAX) { adjustment = 0; } else
adjustment = MAX-height;
230
ToLower.java Continued
231
To do HW 2 Reading: Chapter 4 (pp. 195 - end) – Multiple Selections
Add if statements Reading: Chapter 4 (pp end) – Multiple Selections Bring laptop
232
COMP 14 Introduction to Programming
Adrian Ilie July 1, 2005
233
Quiz Grades
234
Review Topics Comparisons with text Tokenizer objects
Using the debugger Closing curly brace signals the end of an if statement.
235
Review Flow of Execution
236
Two-Way Selection
237
The if-else Statement if (height <= MAX) { adjustment = 0; } else
adjustment = MAX-height;
238
Nested if Statements The general syntax of a nested if statement is:
if (condition1) { block1 } else if (condition2) block2 else block3
239
Nested if Statements has four legs plays fetch doesn't play fetch
if (hasFourLegs) { if (playsFetch) System.out.println ("DOG"); else System.out.println ("CAT"); } else if (hasWings) System.out.println ("BIRD"); System.out.println ("FISH"); doesn't play fetch does not have four legs has wings Assume here that hasFourLegs, playsFetch, and hasWings are boolean variables Which if statements match to which else statements? "else" matches to closest unmatched "if" notice the indentation doesn't have wings
240
The switch Statement
241
The switch Statement Provides another means to decide which statement to execute next Evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements
242
The switch Statement The general syntax of a switch statement is:
switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } switch and case are reserved words Don't need braces in the statement list If expression matches value2, control jumps to here
243
The switch Statement Expression evaluated must be integral type
integer or character, not boolean or floating point Case values must be constant (literal), not variable Can be implemented with nested if statements, but is much clearer with switch statements
244
The switch Statement default break
no case value matches the expression if no default exists and no case value matches the expression, no statements in the switch statement are executed break processing jumps to statement following the switch statement usually at the end of each case Once inside a case, processing continues in order until a break statement is reached
245
The switch Statement System.out.print ("Enter prize code: ");
int prize = Integer.parseInt(keyboard.readLine()); switch (prize) { case 1: System.out.println (“A Brand New Car!”); break; case 2: System.out.println (“A Trip to Hawaii!”); default: System.out.println (“Sorry, Try Again”); }
246
Questions Assume movieRating is an int and movieName is a String switch (movieRating) { case 1: System.out.println ("Run away!"); if (movieName.equals("Gigli")) System.out.println ("Quickly!"); case 2: System.out.println ("Save your money"); break; case 3: System.out.println ("It's OK"); } What is printed if movieRating is 1 and movieName is "Gigli"? What is printed if movieRating is 5? Run away! Quickly! Save your money [Nothing]
247
Questions What is printed with the following values of x and y:
if ((x > 0) && (y < 0)) { z = x+y; System.out.println (“z = ” + z); } System.out.print (“The sum is “); if (x+y < 0) System.out.println(“negative.”) else System.out.println (“positive.”); What is printed with the following values of x and y: x = 5, y = -4 x = -9, y = 5 x = 5, y = 5 z=1 The sum is positive. The sum is negative. The sum is positive.
248
Exercise Rock, Paper and Scissors
Player 1 inputs (R)ock, (P)aper or (S)cissors Player 2 inputs (R)ock, (P)aper or (S)cissors Output message: Input of player A Input of player B Winner (or draw)
249
To do Work on assignment 3. Read ch. 5.
250
COMP 14 Introduction to Programming
Adrian Ilie July 5, 2005
251
Writing Selection Statements What Type of Construct To Use?
Only need to execute additional statements if condition is true Need to execute separate additional statements based on if the condition is true or false Need to execute different statements based on multiple conditions Need to execute different statements based on an expression that evaluates to a char or int if if-else nested if-else switch
252
Writing Selection Statements
Write the outline of the selection statement keywords curly braces case and break statements (for switch) Write the expression boolean expression, or condition expression or variable evaluating to char or int Write statements that execute based on the condition
253
Example Write a selection statement that sets grade to 'F' if score is less than 60 and sets grade to 'P' if score is greater than or equal to 60. 1) Choose construct if-else 2) Write outline if ( ) { } else what type of variable is grade?
254
Example Write a selection statement that sets grade to 'F' if score is less than 60 and sets grade to 'P' if score is greater than or equal to 60. 3) Add condition if (score < 60) { } else 4) Add statements if (score < 60) { grade = 'F'; } else grade = 'P'; what type of variable is grade?
255
Questions What type of selection statement should be used?
Print "Male" if gender is 'M' and "Female" if gender is 'F'. Print the state associated with areaCode, where areaCode is an int. Print the maximum of three integers. if-else switch nested if-else
256
Question Write code that will print:
Assume that the lengths of 3 sides of a triangle are given in the integer variables side1, side2, and side3. Write code that will print: "Equilateral" if all three sides are equal "Isosceles" if only two sides are equal "Scalene" if no sides are equal equilateral isosceles scalene First, what selection construct should be used? nested if-else
257
Answer // side1, side2, and side3 are lengths
// of the sides of a triangle if (side1 != side2 && side2 != side3 && side1 != side3) // no sides are equal System.out.println ("Scalene"); else if (side1 == side2 && side2 == side3) // all sides are equal System.out.println ("Equilateral"); else // two sides are equal System.out.println ("Isosceles");
258
Today Repetition statements while loops for loops
259
Why Is Repetition Needed?
Want to add 5 integers to find their average? declare a variable for each integer initialize the sum read in the user input one at a time sum the numbers take the average Want to add 1000 integers to find their average? declare one variable for input initialize the sum read in one line of user input add to the sum take the average repeat steps 3 and 4 1000 times
260
Repetition Statements
Allow us to execute a statement multiple times Often referred to as loops Controlled by boolean expressions like selection, or conditional, statements Java has three kinds of repetition statements: the while loop the for loop the do loop
261
Loops Must use a loop control variable 4 Parts to Every Loop
controls how many times to loop 4 Parts to Every Loop initialization - set loop control variable before condition condition - when to stop update - change the loop control variable body - actions to repeat
262
Typical Uses of Loops Repeat a section of code a specified number of times - counter-controlled Repeat a section of code (reading input) until a specific value is read - sentinel-controlled Repeat a section of code (reading input) until a valid value is entered - input validation Repeat a section of code (reading from a file) until the end of the file is reached - EOF-controlled Repeat a section of code until a boolean variable becomes false - flag-controlled
263
The while Loop Syntax while ( condition ) { loop body; } while is a
reserved word If the condition is true, the loop body is executed. Then the condition is evaluated again. The loop body is executed repeatedly until the condition becomes false.
264
The while Loop Syntax while (expression) statement
Expression is always true in an infinite loop Statements must change value of expression to false
265
The while Loop Example final int LIMIT = 3; int count = 0;
while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); boolean condition Output: 1 2 All done! initialization Here are the four parts of the loop the update is always inside the loop body in a while loop count is the loop control variable it's what's initialized it's what's updated ++ is the increment operator loop body update
266
The while Loop What's Going On?
final int LIMIT = 3; int count = 0; while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); LIMIT count Output: 3 1 2 3 1 2 All done!
267
The while Loop final int LIMIT = 3; int count = 0; Output: 1
while (count < LIMIT) { count++; System.out.println (count); } System.out.println (“All done!”); Output: 1 2 3 All done! What is output in this case? the update to the loop control variable is performed before the print statement
268
The while Loop final int LIMIT = 3; Output: int count = 0;
while (count < LIMIT) { System.out.println (count); } System.out.println (“All done!”); Output: ... What is output in this case? missing the update statement Infinite loop
269
The while Loop final int LIMIT = 3; int count = 0; Output:
while (count <= LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); Output: 1 2 3 All done! Small modification to the boolean condition
270
The while Loop If the condition of a while statement is false initially, the loop body is never executed The body of a while loop will execute zero or more times
271
Counter-Controlled while Loop
Used when we know exactly the number of times to execute the loop Basic Form: counter = 0; while (counter < N) { ... counter++; } N is the number of times the loop should execute
272
Example final int NUM_STUDENTS = 100; int sum = 0; double average;
int i = 0; // initialize loop control var while (i < NUM_STUDENTS) { sum += Integer.parseInt(inFile.readLine()); i++; // update loop control variable } average = (double) sum / NUM_STUDENTS; Often we use i, j, k as counter variable names. Assume that inFile is a BufferedReader object that reads input from a file sum+=a is the same as sum=sum+a
273
Reading From a File How do you know how many items there will be?
ask the user arrange the data file so that the first item is the number of items in the file Other ways to read all of the items: use sentinel value read until end-of-file (EOF)
274
Sentinel-Controlled while Loop
Used when exact number of entry pieces is unknown but last entry (special / sentinel value) is known Basic Form: input the first data item into variable while (variable != sentinel) { ... input a data item into variable }
275
Example int i = 0, sum = 0, score; final int SENTINEL = -99; double average; // initialize the loop control variable score = Integer.parseInt(inFile.readLine()); while (score != SENTINEL) { sum += score; i++; // update the loop control variable } average = (double) sum / i; Assume that inFile is a BufferedReader object that reads input from a file
276
Average.java Example Read in integers and print their sum until the user enters 0 Print the average of the numbers entered
277
Input Validation while Loop
Used to ensure that the user enters valid input Basic Form: input a data item into variable while (variable is not in valid range) { ask the user for valid input }
278
Example int num; // initialize loop control variable System.out.print (“Enter a number [0-100]: "); num = Integer.parseInt(keyboard.readLine()); while ((num < 0) || (num > 100)) { System.out.println (num + " is not [0-100]"); System.out.print (“Enter a number: “); // update the loop control variable } System.out.println (“You entered “ + num); In this example, we use input validation to make sure that the user enters input in the expected range Loop only executes when input is invalid
279
Flag-Controlled while Loop
Boolean value used to control loop Basic Form: boolean found = false; while (!found) { ... if(expression) found = true; }
280
EOF-Controlled while Loop
Used when input is from a file Sentinel value is not always appropriate Basic Form: inputLine = inFile.readLine(); while (inputLine != null) { ... } Assume that inFile is a BufferedReader object that reads input from a file null is a reserved word
281
Average.java Example Modify example to read from a file
282
To do Finish assignment 3 Bring laptop. Study for Quiz!
Writing a whole program Variables and classes String, StringTokenizer GUI Relational and boolean operators if, if-else, switch while, for loops not in the quiz!!!
283
COMP 14 Introduction to Programming
Adrian Ilie July 6, 2005
284
Homework Collaboration Proper naming of attached files
Declare it or lose points Proper naming of attached files Proper subject Algorithm first, program later I will not help you with a program if you can’t show me at least a tentative algorithm first Be easy on my eyes, use proper indentation Don’t submit it if it doesn’t work, come talk to me instead
285
Loops Allow us to repeat statements some number of times
Must use a loop control variable controls how many times to loop 4 Parts to Every Loop initialization - set loop control variable before condition condition - when to stop update - change to the loop control variable body - actions to repeat
286
The while Loop while (expression) statement
287
Today in COMP 14 The for loop The do...while loop break and continue
Nested loops
288
The for Loop Specialized form of while loop
Simplifies the writing of count-controlled loops Basic Form: for (initialization; condition; update) { statement(s); }
289
The for Loop Execution initial statement executes
loop condition evaluated If loop condition evaluates to true, execute for loop statement and execute update statement Go back to step 2 and repeat until loop condition is false
290
The for Loop Syntax for ( initialization; condition; update ) {
The initialization is executed once before the loop begins The loop body is executed until the condition becomes false Reserved word for ( initialization; condition; update ) { loop body; } The update portion is executed at the end of each iteration The condition-loop body-update cycle is executed repeatedly
291
for vs. while A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { loop body; update; } In a while loop, the update is part of the loop body In a for loop, it's on the outside of the loop body
292
The for Loop Example final int LIMIT = 3; int count;
for (count=0; count<LIMIT; count++) { System.out.println (count); } System.out.println (“All done!”); Output: 1 2 All done! boolean condition initialization update loop body
293
Comparing while and for
While Loop final int LIMIT=3; int i = 0; while (i < LIMIT) { System.out.println (i); i++; } System.out.println (“All done!”); For Loop final int LIMIT=3; int i; for (i=0; i<LIMIT; i++) { System.out.println (i); } System.out.println ("All done!"); for loop is interesting because it might be more efficient on some CPUs
294
Watch out! for statement ending in semicolon is empty; does not affect program while statement ending in semicolon results in infinite loop for (count=0; count<LIMIT; count++); while (count<LIMIT);
295
Examples Hello * Hello * * for (i=1; i<=5; i++) {
System.out.println ("Hello"); System.out.println ("*"); } Hello * Hello * for (i=1; i<=5; i++) System.out.println ("Hello"); System.out.println ("*"); for (i=1; i<=5; i++); System.out.println ("*"); *
296
In-Class Exercise for vs. while Loops
Output: 3 6 9 12 15 18 final int MAX = 20; int i; for (i = 0; i<MAX; i+=3) { System.out.println (i); } Predict the output The counter variable may not be incremented by 1!!! It may also be decremented
297
In-Class Exercise for vs. while Loops
final int MAX = 20; int i; for (i = 0; i<MAX; i+=3) { System.out.println (i); } Translate this to a while loop. final int MAX = 20; int i = 0; while (i < MAX) { System.out.println (i); i += 3; }
298
The do...while Loop Syntax
{ loop body; } while ( condition ); do and while are reserved words The loop body is executed once initially, and then the condition is evaluated Notice the semicolon at the end of the while line The loop body is executed repeatedly until the condition becomes false
299
do…while Loop (Post-test Loop)
statement(s); } while (expression);
300
The do...while Loop Like a while loop, but its condition is at the end of the loop Loop body always executes at least once Must also be checked for termination (not an infinite loop) Anything you can do with a do...while loop, you can do with a while loop
301
The do...while Loop Example
Output: 1 2 All done! final int LIMIT = 3; int count = 0; do { System.out.println (count); count++; } while (count < LIMIT); System.out.println (“All done!”); update initialization loop body The update is still inside the loop body But, the boolean condition is at the end of the do loop boolean condition
302
Comparing while and do...while
while Loop final int LIMIT=3; int count = 0; while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); do...while Loop final int LIMIT=3; int count = 0; do { System.out.println (count); count++; } while (count < LIMIT); ("All done!");
303
while vs. do...while i = 11; while (i <= 10) {
System.out.print (i); i += 5; } System.out.println(); [blank line] i = 11; do { System.out.print (i); i += 5; } while (i <= 10); System.out.println(); 11
304
In-Class Exercise The do...while Loop
x y 0 0 Output: int x = 0, y = 0; do { System.out.println (x*y); if (y < x) { y += 2; } x++; } while (x < 5); Predict the output of the loop 1 2 2 3 4 4 5 Hint: Make a table to help keep up with the values of x and y as the loop progresses 4 6 16
305
break Statements Used to exit early from a loop
Used to skip remainder of switch structure Can be placed within if statement of a loop If condition is met, loop exited immediately
306
break Example in Output 1.0 1.00 2.0 0.50 4.0 0.25 0.0 double in;
while (true) { in=Double.parseDouble( keyboard.readLine()); if (in == 0.0) break; } System.out.println (1.0 / in); in Output 0.0
307
continue Statements Used in while, for, and do...while structures
When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop When executed in a while/do…while structure, expression evaluated immediately after continue statement In a for structure, the update statement is executed after the continue statement; then the loop condition executes
308
continue Example in Output 1.0 1.00 2.0 0.50 4.0 0.25 0.0 5.0 0.20
double in; while (true) { in=Double.parseDouble( keyboard.readLine()); if (in == 0.0) continue; } System.out.println (1.0 / in); in Output 0.0 infinite loop
309
Nested Control Structures
Provides new power, subtlety, and complexity if, if…else, and switch structures can be placed within while loops for loops can be found within other for loops each time through the outer loop, the inner loop goes through its full set of iterations
310
Nested Control Structures Example
for (int row = 1; row <= 5; row++) { for (int star = 1; star <= row; star++) System.out.print(“*”); } System.out.println(); Output: * ** *** **** ***** we can put the declaration of the loop control variable in the header of the for loop, but the variable cannot be used outside the loop Can't use the variable row outside the outer for loop. Can't use the variable star outside the inner for loop.
311
Exercise Printing Patterns
Use nested for loops * * *
312
To do Assignment 4 Read ch. 6
313
COMP 14 Introduction to Programming
Adrian Ilie July 8, 2005
314
COMP 14 So Far... Problem Solving Mathematical Calculations Output
User Input File I/O Selection (if, if-else, switch) Loops (while, do...while, for) Basic programming blocks.
315
COMP 14 Next... Object-Oriented Design Writing Methods Writing Classes
pieces of code that we give a name Writing Classes organize related pieces of information Arrays access multiple pieces of information with a single identifier
316
Object-Oriented Design
What is it? Designing a solution to a problem by first identifying components called objects, and determining how the objects interact with each other
317
Objects VCR Example Use it without knowing how it's made
Internal parts are hidden -- only interact with the provided buttons Can't modify the functions of a VCR -- record button always records, play button always plays Same is true for objects (like Strings) that are provided by Java
318
Objects Consist of data and operations on the data
Data - descriptive characteristics Operations - what it can do (or what can be done to it) Example A coin that can be flipped so that its face shows either "heads" or "tails" data: its current face (heads or tails) operations: it can be flipped Operations can change data.
319
Objects And Methods and Classes
We represent operations with methods group of statements that are given a name We can use objects and their methods without knowing exactly how the methods work An object is an instance of a class. A class is the blueprint of an object. the class provides the methods that can operate on an object of that class
320
Classes A class contains data declarations and method declarations
A class is a description of an object just a model, not an actual object you can think of the concept of a book without thinking of a particular book A class is no more an object than a blueprint is an actual house
321
Object-Oriented Design Simplified Methodology
Write down detailed description of problem Identify all (relevant) nouns and verbs From list of nouns, select objects Identify data components of each object From list of verbs, select operations
322
Object-Oriented Design Example 1
Problem Statement Write a program to input the length and width of a rectangle and calculate and print the perimeter and area of the rectangle
323
Example 1 Building a Rectangle
Identify nouns length, width, rectangle, perimeter, area Identify each class length of a rectangle width of a rectangle perimeter of a rectangle area of a rectangle
324
Example 1 Building a Rectangle
Identify data members for each class nouns: length, width, area, perimeter what are the essential nouns for describing the rectangle? area and perimeter can be computed if we know the length and width
325
Example 1 Building a Rectangle
Identify operations for each class input, calculate, print setLength setWidth computePerimeter computeArea print getLength getWidth directly from problem statement customary to include operations to get the value of the data members
326
class Rectangle Data Members and Operations
class name data members operations (methods) Last Step: design and implement an algorithm for each operation
327
Anatomy of a Class A class contains data declarations and method declarations int width; int length; Data declarations All methods belong to a particular class and operate (or access) objects of that class The data and methods of a class are called its members Method declarations (operations)
328
Classes and Objects length = 15, width = 3 length = 20, width = 6
A class (the concept) An object (the realization) length = 15, width = 3 Rectangle length = 20, width = 6 Multiple objects from the same class length = 15, width = 15
329
Object-Oriented Design Example 2
A place to buy candy is from a candy machine. A new candy machine is bought for the gym, but it is not working properly. The candy machine has four dispensers to hold and release items sold by the candy machine and a cash register. The machine sells four products —candies, chips, gum, and cookies—each stored in a separate dispenser. You have been asked to write a program for this candy machine so that it can be put into operation.
330
Object-Oriented Design: Example 2
The program should do the following: Show the customer the different products sold by the candy machine. Let the customer make the selection. Show the customer the cost of the item selected. Accept money from the customer. Return change. Release the item, that is, make the sale.
331
Object-Oriented Design: Example 2
332
Object-Oriented Design: Example 2
333
Non-Concrete Objects Objects in programs don't always have real-world analogs Example object: error message data: text of the error message operation: print the text of the error message to the screen
334
Next in Comp14 Tomorrow: writing methods Monday: review for mid-term
Bring laptops Write questions before coming to class
335
COMP 14 Introduction to Programming
Adrian Ilie July 8, 2005
336
Anatomy of a Class A class contains data declarations and method declarations int width; int length; Data declarations All methods belong to a particular class and operate (or access) objects of that class The data and methods of a class are called its members Method declarations (operations)
337
Writing a class public class Rectangle { // data members
private int width; private int length; // methods public double computeArea() … public static void main() } In a class, we combine data members and methods. This week we’ll learn how to write classes. Today we start with methods.
338
Why Use Methods? To divide complex programs into manageable pieces
Abstraction provide an operation to be performed on an object (ex: computeArea) Code Re-use write a small piece of code that can be used (called) multiple times (saves typing)
339
Methods Pre-defined methods User-defined methods
provided by Java standard library we've used these before Math class (Math.pow, Math.sqrt, ...) Integer class (Integer.parseInt, ...) User-defined methods you write these
340
Internal data members of the class
Method as a Black Box METHOD Input parameters Return value Internal data members of the class A method can use input parameters and internal data members of the class It may modify the value of internal data members It may also return a value
341
Control Flow Program control flow Method control flow
execution always begins with the first statement in the method main other methods execute only when called Method control flow when a method is invoked, the flow of control jumps to the method and the computer executes its code when complete, the flow of control returns to the place where the method was called and the computer continues executing code Test this with the debugger!
342
Example: Rectangle.java
This is just to see an example of using methods.
343
Using Methods What You Need To Know
Name of the method Number of parameters Data type of each parameter Data type of value computed (returned) by the method The code required to accomplish the task
344
Method Declaration Specifies the code that will be executed when the method is invoked (or called) Located inside a class definition Contains method header method body
345
Method Header A method declaration begins with a method header
public static int countCharInWord (char ch, String word) visibility modifiers method name formal parameter list return type visibility modifiers -- public if this method can be used (called) from outside the current class/file, private otherwise static -- means that although this method belongs to a class, we don't need to use any member variables in the method body we'll use public and static (like main) for now and talk about when to use private next week return type -- what data type will be returned from the method method name -- naming convention (verbs, start w/lowercase, new words start uppercase) The formal argument list contains the type and name of the variables. These variables will be used in the method body, they do not have to be previously defined The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter
346
Return Value Value-returning methods Void methods
The method returns the result of some operations Like mathematical functions Return one single value Void methods Perform operations but return no value
347
Value-Returning Methods
Think mathematical function f(x) = 2x + 5 f(x, y) = 2x + y f(1) = 7 f(1, 5) = 7 f(2) = 9 f(2, 3) = 7 f(3) = 11 f(3, 1) = 7 Can have multiple arguments (parameters) Only one result of the function
348
Value-Returning Methods Uses
Save the value for future calculation Use the value in a calculation Print the value x = Math.pow (y, 2); z = a + Math.pow (y, 2) + x; System.out.println (Math.pow (y, 2));
349
Return Type Indicates the type of value that the method evaluates to:
primitive data type class name void reserved word indicating that nothing is returned When a value is returned, the method call is replaced with the returned value In this example, 'e' and "Heels" are called actual parameters -- because they are the actual values that we want the method to use. int number = countCharInWord ('e', "Heels"); 2
350
The return Statement Tells the computer to "return" back to where the call was originally made. Specifies the value that will be returned return expression; The data type of expression must match the method's return type Methods with return types of void usually don't (but can) have a return statement Value-returning methods must have at least one return statement
351
Using return These are equivalent methods.
public static double larger (double x, double y) { double max; if(x >= y) max = x; else max = y; return max; } These are equivalent methods. public static double larger (double x, double y) { if(x >= y) return x; else return y; }
352
Example: Rectangle.java
Add computePerimeter( )
353
Void Methods Do not return a value Have a return type of void
Similar in structure to value-returning methods Call to method is always a stand-alone statement Can use return statement to exit method early
354
Example: Rectangle.java
Add printPerimeter( )
355
The main Method The main method looks just like all other methods
public static void main (String[] args) modifiers return type method name parameter list
356
Method Body The method header is followed by the method body
public static int countCharInWord (char ch, String word) { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count; ch and word are local data They are created each time the method is called, and are destroyed when it finishes executing The return expression must be consistent with the return type
357
Example: Largest.java Read a sequence of numbers Print the max
358
Parameters Each time a method is called, the actual parameters in the call are copied into the formal parameters int num = countCharInWord ('e', "Heels"); public static int countCharInWord (char ch, String word) { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count;
359
Parameters Formal parameters Actual parameters printStars (35);
variable declarations in the method header automatic local variables for the method Actual parameters actual values that are passed to the method can be variables, literals, or expressions printStars (35); printStars (30 + 5); int num = 35; printStars (num);
360
Parameters Primitive Data Type Variables
If a formal parameter is a variable of a primitive data type, can it be modified inside a method? The value from the actual parameter is copied There is no connection between variables inside the method and outside Conclusion: it cannot be modified!!
361
Example: Largest.java Modify the values inside the comparison method
362
Parameters Reference Variables
If a formal parameter is a reference variable, can the object be modified inside a method? The address from the actual parameter is copied The local reference variable points to the same object Conclusion: it can be modified!!
363
Primitive Data Types What if we want to modify a variable of a primitive data type inside a method? Encapsulate it in a class Example: IntClass (ch. 6, p. 306/350) IntClass is a class suggested in the book, but it is not a built-in class in Java!!!
364
Data Scope The scope of data is the area in a program in which that data can be used (referenced) Data declared at the class level can be used by all methods in that class Data declared within a method can be used only in that method also called local data Key to determining scope is to look for blocks of code (surrounded by { }) variables declared inside { } cannot be used outside recall the problems some had with variables declared inside if statements
365
Data Scope Example public class Rectangle {
// variables declared here are class-level // available in all methods in Rectangle class public int computeArea() // variables declared here are method-level // only available in computeArea() } public void print() // only available in print()
366
Overloading Methods Overloading - the process of using the same method name for multiple methods The signature of each overloaded method must be unique number of parameters type of the parameters not the return type of the method, though The compiler determines which version of the method is being invoked by analyzing the parameters
367
Overloading Methods public static double tryMe (int x) {
return x ; } Version 1 Invocation result = tryMe (25, 4.32) public static double tryMe (int x, float y) { return x*y; } Version 2
368
Overloaded Methods println Example
The println method is overloaded: println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);
369
To do Monday: practice for mid-term
Bring laptops Collect questions Pick examples that we have done so far and convert parts of the code to methods Binary.java (homework 2) AverageKeyboard.java AsteriskPattern.java …
370
COMP 14 Introduction to Programming
Adrian Ilie July 11, 2005 Hand out syllabus if necessary Intro myself again Go through class roll.
371
Parts of the Computer hardware ________- computer components including the CPU, main memory, I/O devices, and secondary storage ________ - the brain of the computer, containing the CU, PC, IR, ALU, and ACC ________ - computer instructions to solve a problem The digits 0 and 1 are called _________ or the shortened term ________ CPU program Digits that can only take the values 0 and 1. binary digits bits
372
Questions - Hardware ____________- points to the next instruction to be executed ____- a unique location in memory ____________- stores information permanently Instructions executed by the CPU must be first loaded to ________ program counter (PC) address secondary storage main memory
373
Questions - Software Classify the following pieces of software as operating system or application: Microsoft Windows 2000 Microsoft PowerPoint Linux Your COMP 14 programs OS app OS app
374
Questions - Binary 26-1=63 25*1+24*1+23*1+22*0+21*1+20*0=58
What’s the maximum value a 6-bit number can represent? What’s the decimal representation of ? What’s the binary representation of 35? 26-1=63 25*1+24*1+23*1+22*0+21*1+20*0=58 5 minutes to work on these. Then show the calculator in the computer. 3510=
375
Questions: Java Basics
syntax The ________ rules of a language determine which instructions are valid. True or False? Hello! is an example of a legal Java identifier. _______ If an operator has an integer and a floating-point operand, the result of the operation is a ___________ number. The expression (int) (9.2) evaluates to ___. False floating-point 9
376
Questions – Identifiers
Classify the following as legal or illegal identifiers: My First Program ____ my1stProgram ____ 1stProgram ____ $money ____ an_identifier ____ Jane'sProgram ____ illegal legal illegal legal legal illegal
377
Questions - Expressions
9 % 6 3 (5 + 4) % 6 (5 + 6) % 3.5 (double) (13) / 2 (double) (13 / 2) 11 % 3.5 not possible 13.0 / 2 6.5 (double) (6) 6.0
378
Questions - Assigning What is stored in the memory location referred to by the identifier num after each of the following statements is executed in order? int num; ______ num = 5; ______ num = ; ______ num = num * 3; ______ num = ; ______ unknown 5 7 21 error would give an error since would not result in an int
379
Questions – Valid Statements
Which of the following are valid Java assignment statements? Assume that i, x, and percent have been declared as double variables and properly initialized. i = i + 5; ______ x + 2 = x; ______ x = 2.5 * x; ______ percent = 10%; ______ valid invalid valid invalid
380
Questions – Variables and Objects
True or False. A primitive variable is a variable that stores the address of a memory space. ______ The operator ____ is used to create a class object. In Java, the ________ operator is used to access members of a class. It separates the class (or object) name from the method name. True or False. Class objects are instances of that class. ______ False new dot (.) True
381
Decimal Format Examples
DecimalFormat twoDecimal = new DecimalFormat("0.00"); DecimalFormat fmt = new DecimalFormat("0.##"); System.out.println (twoDecimal.format(56.379)); _______ System.out.println (fmt.format(56.379)); _______ System.out.println (twoDecimal.format(.3451)); _______ System.out.println (fmt.format(.3451)); _______ System.out.println (twoDecimal.format(.3)); _______ System.out.println (fmt.format(.3)); _______ 56.38 56.38 0.35 0.35 0.30 0.3
382
Comparing Characters 'a' > 'A' '6' < 7 ' ' <= 's'
97 > true 54 < false lowercase letters appear later in the ASCII code than uppercase letters, so the value of 'a' is greater than the value of 'A' the character 6 is represented by 54 in the ASCII table, which is greater than 7 space comes before any of the letters in the ASCII table 32 <= true
383
Comparing Floating-Point
3.0 / 7.0 2.0 / 7.0 (3.0 / 7.0) + (2.0 / 7.0) + (2.0 / 7.0) == 1 false If we did this math with exact arithmetic, this expression would be true
384
Comparing Strings Given String str = "Homer"; str.compareTo("Marge")
str.equals("homer") str.compareTo("Bart") negative value false positive value
385
Boolean Operators NOT ! (unary) AND && (binary) OR || (binary) true
!(2+2==5) AND && (binary) (2+2==5) && (1+1==2) OR || (binary) (2+2==5) || (1+1==2) true false true
386
Questions boolean ch < 'A' or ch > 'Z' compareTo
What type of primitive variable can the result of a logical expression be stored in? _______ Under what conditions would the expression ((ch >= 'A') && (ch <= 'Z')) evaluate to false? ______________________ What method do you use to compare two Strings? __________ Why is 'a' greater than 'A'? ______________________________________ boolean ch < 'A' or ch > 'Z' compareTo 'a' comes after 'A' in the ASCII character table
387
Questions false true true true int count = 0, sum = 54;
Given the following declarations, evaluate each Boolean expression: int count = 0, sum = 54; double x = 4.3, y = 1.2; boolean wrong = true; (wrong && sum > 60) ((x > 5) || !(sum == 55)) !((y > 1.0) && (x < 4)) ((count != 4) || (sum > 100) && wrong) false (true && false) true && is evaluated before || (false || !(false)) true !(true && false) true (true || false && true) (true || false)
388
Questions Assume movieRating is an int and movieName is a String switch (movieRating) { case 1: System.out.println ("Run away!"); if (movieName.equals("Gigli")) System.out.println ("Quickly!"); case 2: System.out.println ("Save your money"); break; case 3: System.out.println ("It's OK"); } What is printed if movieRating is 1 and movieName is "Gigli"? What is printed if movieRating is 5? Run away! Quickly! Save your money [Nothing]
389
Questions What is printed with the following values of x and y:
if ((x > 0) && (y < 0)) { z = x+y; System.out.println (“z = ” + z); } System.out.print (“The sum is “); if (x+y < 0) System.out.println(“negative.”) else System.out.println (“positive.”); What is printed with the following values of x and y: x = 5, y = -4 x = -9, y = 5 x = 5, y = 5 z=1 The sum is positive. The sum is negative. The sum is positive.
390
Selection Statements What type of selection statement should be used?
Print "Male" if gender is 'M' and "Female" if gender is 'F'. Print the state associated with areaCode, where areaCode is an int. Print the maximum of three integers. if-else switch nested if-else
391
Loops final int MAX = 20; int i; for (i = 0; i<MAX; i+=3) {
System.out.println (i); } Translate this to a while loop. final int MAX = 20; int i = 0; while (i < MAX) { System.out.println (i); i += 3; }
392
Object-Oriented Design Simplified Methodology
Write down detailed description of problem Identify all (relevant) nouns and verbs From list of nouns, select objects Identify data components of each object From list of verbs, select operations
393
COMP 14 - 03 Introduction to Programming
Adrian Ilie July 13, 2005
394
Today in Comp 14 Review Classes and Methods Rectangle class
ReverseString class
395
Data Scope Example public class Rectangle {
COMP 14 Data Scope Example public class Rectangle { // variables declared here are class-level // available in all methods in Rectangle class public int computeArea() // variables declared here are method-level // only available in computeArea() } public void print() // only available in print()
396
Review Overloading Methods
COMP 14 Review Overloading Methods Overloading - the process of using the same method name for multiple methods The signature of each overloaded method must be unique Number of parameters Type of the parameters not the return type of the method, though The compiler determines which version of the method is being invoked by analyzing the parameters
397
Constructors Constructors can be overloaded, too.
COMP 14 Constructors public class Rectangle { private int length; private int width; Rectangle r2 = new Rectangle (5, 10); public Rectangle () { length = 0; width = 0; } Constructors can be overloaded, too. public Rectangle (int l, int w) { length = l; width = w; }
398
Creating and Using Objects
COMP 14 Creating and Using Objects r Create an object: Rectangle r; r = new Rectangle(2, 3); OR Rectangle r = new Rectangle(2, 3); Use the object and the dot operator to access methods: r.setLength(5); r.setWidth(10); 2500 2500 2 3 Now, that we have an implementation of Rectangle, how can we use it? The first line creates a reference variable (holds an address). The second line creates the Rectangle object and stores the address where the object was created in the reference variable r. r 2500 2500 5 2 10 3
399
COMP 14 Exercise Write a method for the Rectangle class called printBox that will print the rectangle as a box made of % example: length = 3, width = 5 %%%%% % %
400
COMP 14 public void printBox () { for (int i = 1; i <= width; i++) System.out.print("%"); System.out.println( ); for (int i = 1; i <= length - 2; i++) { System.out.print("%"); for (int j = 1; j <= width - 2; j++) System.out.print(" "); System.out.println("%"); } for (int i = 1; i <= width; i++) System.out.print("%"); System.out.println( ); } length = 3, width = 8 %%%%%%%% % % %%%%%%%%
401
public void printBox () { for (int i = 1; i <= width; i++) System.out.print("%"); System.out.println( ); for (int i = 1; i <= length - 2; i++) { System.out.print("%"); for (int j = 1; j <= width - 2; j++) System.out.print(" "); System.out.println("%"); } for (int i = 1; i <= width; i++) System.out.print("%"); System.out.println( ); } COMP 14 length = 8, width = 3 %%% % % % % % % % % % % % % %%%
402
Testing public class RectangleTester { public static void main (String[] args) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle (20, 30); r1.setWidth(5); r1.setLength(10); r1.print(); r2.print(); System.out.println(r1); System.out.println(r2); } } // end of RectangleTester class What if we just wanted to output r1 and r2 using System.out.println?
403
The toString Method Special method in Java classes
COMP 14 The toString Method Special method in Java classes Produces a String object based on the current object, suitable for printing Mapped to the '+' operator Also called when the object is a parameter in a print() or println() method There is a default toString method, but it's better if we write our own System.out.println(r1); System.out.println(r1.toString());
404
Rectangle.java length: 2 width: 3 public String toString() {
COMP 14 Rectangle.java public String toString() { String result = ""; result += "length: " + length + "\n"; result += "width: " + width; return (result); } Show example in jGRASP with debug to show that toString is automatically called. Rectangle r = new Rectangle (2,3); System.out.println (r); length: 2 width: 3
405
Rectangle.java What if we wanted to print out the box when we say System.out.println(r1)?
406
Rectangle.java Which length and which width?? public class Rectangle {
COMP 14 Rectangle.java public class Rectangle { private int length; private int width; public Rectangle (int length, int width) length = length; width = width; } Which length and which width??
407
The Reference this Reserved word
COMP 14 The Reference this Reserved word Refers to instance variables and methods of a class Allows you to distinguish between member variables and local variables with the same name
408
Rectangle.java public class Rectangle { private int length;
COMP 14 Rectangle.java public class Rectangle { private int length; private int width; public Rectangle (int length, int width) this.length = length; this.width = width; }
409
ReverseString.java Available on course web page ReverseTester.java
Fully commented ReverseTester.java Driver class : Tests the ReverseString class Also available online
410
Review Classes and Methods ReverseString.java
When do you use dot operator (.) to access methods? ReverseString r1 = new ReverseString( keyboard.readLine() ); // Output the reverse of the entered string System.out.println("The reverse of the string is " + r1.getReverse() ); Inside ReverseTester.java Dot operator to access method getReverse()
411
Review Classes and Methods ReverseString.java
When do you use dot operator (.) to access methods? ReverseString r1 = new ReverseString( keyboard.readLine() ); // Output the reverse of the entered string System.out.println("The reverse of the string is " + r1.getReverse() ); public ReverseString(String s){ original = s; computeReverse(); } Inside ReverseString.java No dot operator to access computeReverse()
412
Review Classes and Methods ReverseString.java
When do you use dot operator (.) to access methods? Must use dot operator to access method that is in a different class To access a method in ReverseString from ReverseTester, use dot operator To access a method in ReverseString from ReverseString, NO dot operator
413
Review Classes and Methods ReverseString.java
When do you use public vs. private? private void computeReverse(){ // method body } public boolean isPalindrome(){ // method body } Only called from ReverseString class Called from ReverseTester class Where are these methods called from? (What class are they accessed in?)
414
Review Classes and Methods ReverseString.java
When do you use public vs. private? Use private: When the method or data member is only going to be accessed inside the same class Use public: When the method or data member is going to be accessed outside the class Anything that is called, or used, inside ReverseTester class must be public
415
Review Classes and Methods ReverseString.java
Why did we not use static in ReverseString class? When and why do we use static? How do we access static methods or variables from another class?
416
Review Classes and Methods ReverseString.java
Why did we not use static in ReverseString class? When and why do we use static? How do we access static methods or variables from another class? This method must be declared static inside class classname classname.methodname() Example: Integer.parseInt(“48”); public static int parseInt(String s) Dot operator
417
Review Classes and Methods ReverseString.java
Why did we not use static in ReverseString class? When and why do we use static? Do not need object to use method/variable Consistent among all objects Shared among all objects of the class
418
Review Classes and Methods ReverseString.java
Why did we not use static in ReverseString class? When and why do we use static? Want all objects of class to share one copy of data Do not need method/variable to be object specific NOTE: Can't call a non-static method from a static method Can't access non-static variables from a static method
419
Review Classes and Methods ReverseString.java
Why did we not use static in ReverseString class? NOTE: Can't call a non-static method from a static method Can't access non-static variables from a static method main method is static, therefore myMethod() must also be static within same class public static void main (String[] args) { myMethod(); } public static void myMethod ( ) { // method body }
420
Review Classes and Methods ReverseString.java
Why was there no main method in ReverseString class? Only a driver class (a class that tests your program) has a main method General rule: For each program you write, there will only be one main method Here, it was given in ReverseTester class
421
Review Classes and Methods ReverseString.java
Why was there no keyboard input in ReverseString class (keyboard.readLine())? Keyboard input already performed in ReverseTester How did we give input to ReverseString class??
422
Review Classes and Methods ReverseString.java
Why was there no keyboard input in ReverseString class (keyboard.readLine())? How did we give input to ReverseString class?? Parameters Specifically, in this example, parameter to the constructor public ReverseString(String s){ original = s; computeReverse(); } Formal Parameter Inside ReverseString class
423
Review Classes and Methods ReverseString.java
Why was there no keyboard input in ReverseString class (keyboard.readLine())? How did we give input to ReverseString class?? Parameters ReverseString r1 = new ReverseString( keyboard.readLine() ); Inside ReverseTester class Actual Parameter public ReverseString(String s){ original = s; computeReverse(); } Formal Parameter Inside ReverseString class
424
Review Classes and Methods ReverseString.java
Why didn’t we use System.out.println in the ReverseString class? Output to the screen already performed in ReverseTester How did we give information to ReverseTester class for output?
425
Review Classes and Methods ReverseString.java
Why didn’t we use System.out.println in the ReverseString class? How did we give information to ReverseTester class for output? Return from Methods Specifically, in this example: System.out.println("The reverse of the string is " + r1.getReverse() ); Inside ReverseTester class Call to getReverse() will be replaced with a String return type Inside ReverseString class public String getReverse(){ return reverse; }
426
Review Classes and Methods ReverseString.java
Why didn’t we use System.out.println in the ReverseString class? How did we give information to ReverseTester class for output? Return from Methods Specifically, in this example: System.out.println("The reverse of the string is " + r1.getReverse() ); Inside ReverseTester class Replaced with the value of reverse public String getReverse(){ return reverse; } Inside ReverseString class
427
Communication between Classes
Methods provide communication between methods Parameters provide input into class Return value provides output public returnType methodName ( formal parameters ) Output from method Input to method
428
Question Write a program that takes in 5 int values, computes the sum, and then prints the values in reverse order.
429
Solution What if we wanted to add and print 100 values?
int num0, num1, num2, num3, num4; int sum; System.out.println("Enter five integers, one per line "); num0 = Integer.parseInt(keyboard.readLine()); num1 = Integer.parseInt(keyboard.readLine()); num2 = Integer.parseInt(keyboard.readLine()); num3 = Integer.parseInt(keyboard.readLine()); num4 = Integer.parseInt(keyboard.readLine()); sum = num0 + num1 + num2 + num3 + num4; System.out.println("The sum of the numbers = " + sum); System.out.println(num4 + " " + num3 + " " + num2 + " “ + num1 + " " + num0); What if we wanted to add and print 100 values?
430
COMP 14 Introduction to Programming
Adrian Ilie July 14, 2005
431
Arrays An array is a list of values that can be represented by one variable Members of an array must all have the same data type Each value is stored at a specific, numbered position in the array the number corresponding to each position is called an index or subscript All arrays have a length number of elements the array can hold
432
The array (variable) name
Declaring Arrays The array (element) data type Empty square brackets type[] name; The array (variable) name Creates a reference variable called name that can point to an array of type elements.
433
Declaring Arrays Examples
// array of counters (integers) int[] counter; counter // array of characters char[] characterSet; characterSet // array of grades (doubles) double[] grade; grade
434
The assignment operator
Instantiating Arrays You must instantiate (create) arrays the size of an array is typically not known before run time The assignment operator The array (variable) name The new operator name = new type[size]; The array (element) data type The number of elements
435
Instantiating Arrays Examples
counter // instantiate an array of counters counter = new int[5]; 1 2 3 4 0 <= index < size // instantiate the array of grades numStudents = 10; grade = new double[numStudents];
436
Declaration and Instantiation
type[] name = new type[size]; Declaration Instantiation
437
Example int[] num = new int[5];
438
Array Access Examples double score[] = new score[3]; score[0] = 98.3;
averageScore = (score[0]+score[1]+score[2])/3; numStudents = 3; totalScore = 0; for (int i = 0; i < numStudents; i++) { totalScore += score[i]; } averageScore = totalScore/numStudents; often use loops for access
439
Array Length Arrays have length an internal variable called length
number of elements in array access the length variable using the “dot’ notation (arrayname.length) // loop through the array of test scores sumOfScores = 0; for (int i=0; i<scores.length; i++) { sumOfScores += scores[i]; }
440
Initializing Arrays Array elements are variables too! When and how?
if you don’t initialize, the contents are undefined When and how? if you don’t yet know the size initialize at run time, typically with a loop if you know how many elements perhaps use an initializer list int counter[] = {0, 0, 0, 0, 0}; char[] characterSet = {‘a’,’b’,’c’}; // etc.
441
Initializer Lists List the initial value for the elements of an array
Items are separated by commas and the list is in braces {} The size of the array is determined by the number of items in the list int[] scores = {87, 98, 45}; Can only be used in the same statement as declaring the array NOT int[] scores; scores = {87, 98, 45};
442
Array Bounds Arrays have finite size
If you access an element outside of the array, you’ll get an ArrayIndexOutOfBounds Exception Example: int grades[] = {99, 98, 95, 96}; System.out.println (grades[4]);
443
Example Specify Array Size During Program Execution
(Assume that keyboard has already been declared and instantiated.) int arraySize; System.out.print ("Enter the size of the array:"); arraySize = Integer.parseInt(keyboard.readLine()); int[] list = new int[arraySize];
444
Example Initialize Array to Specific Value (10.00)
(Assume that sale has already been declared and instantiated.) for (int ind = 0; ind < sale.length; ind++) { sale[ind] = 10.00; } sale is a double array (how can we tell?)
445
Example Read Data into Array
(Assume that sale has already been declared and instantiated, and that keyboard has already been declared and instantiated.) for (int ind = 0; ind < sale.length; ind++) { sale[ind] = Double.parseDouble(keyboard.readLine()); } sale is a double array
446
Example Print Array for (int ind = 0; ind < sale.length; ind++) {
(Assume that sale has already been declared and instantiated.) for (int ind = 0; ind < sale.length; ind++) { System.out.print(sale[ind] + " "); }
447
Parallel Arrays Arrays are parallel if corresponding components hold related information String[] studentName; double[] studentGPA; For example, studentName and studentGPA are parallel if studentGPA[3] is the GPA of the student with studentName[3].
448
In-Class Exercises Declare an array of integers called numbers
Declare and instantiate an array of 26 characters called alphabet
449
In-Class Exercises Declare an array of 5 characters called grades and initialize it with the letters: A, B, C, D, F Hint: type[] name = {initialization list}; Write a loop to print the contents of an array named zipCodes Hint: to access array element name[index]
450
In-Class Exercises Write a loop to change all the values of the integer array numbers to index + 1
451
Exercises 1. Find Sum and Average of Array
2. Determine Largest and Smallest Elements in Array sale is a double array
452
Homework 6 (practice) Read data from file Fill arrays with data
Fill objects with data
453
Tomorrow More Arrays Homework 5 due Sunday midnight Bring laptops!!!
arrays of objects passing arrays as parameters searching and sorting Homework 5 due Sunday midnight Bring laptops!!!
454
COMP 14 Introduction to Programming
Adrian Ilie July 18, 2005
455
Review Homework 5 Algorithm How to solve the problem without objects
not totally true, Strings are objects too How to solve the problem with objects
456
Algorithm Create teams Create semifinal games Output initial message
Get score of semifinal 1 Determine finalist 1 Get score of semifinal 2 Determine finalist 2 Create final game Get score of final Determine winner
457
Without objects String UNC=“UNC”; String Duke=“Duke”;
String semi1=UNC + “ Vs. ” + Duke; String finalist1; … if(score1 > score2) finalist1=UNC; else finalist1=Duke;
458
Add method String UNC=“UNC”; String Duke=“Duke”;
String semi1=UNC + “ Vs. ” + Duke; String finalist1; … finalist1=gameWinner(score1, score2, UNC, Duke);
459
With objects Team UNC=new Team(“UNC”); Team Duke=new Team(“Duke”);
Game semi1=new Game(UNC, Duke); Team finalist1; … finalist1=semi1.gameWinner(score1, score2);
460
What’s going on? String name=“UNC” String name=“Duke” Team team1
Team UNC Team Duke Game semi1 Team finalist1 Team objects String name=“Duke” Reference variables Team team1 Team team2 Game object
461
What is different? We declare data inside objects, not directly in the main() method The Strings become data members of the Team objects We no longer need Strings for the games If we don’t use objects, we duplicate the data. The String for the game can be generated using the ones stored in the Teams. The method gameWinner is a method associated to a particular game object No need to pass the game as a parameter. No need to pass the teams as parameters Why does the code look almost the same? Because Strings and Teams and Games are ALL classes/objects Our classes are simply wrappers of Strings
462
Structure of a Team object
Data String name Methods Constructors toString()
463
Structure of a Game object
Data Pointer to team1 (Team team1) Pointer to team2 (Team team2) Methods Constructors toString() gameWinner() receives as parameter the score, and returns the pointer to the winner team.
464
Classes Objects are collections of data and operations (methods)
We need to define the pattern/footprint of objects classes!!!
465
Writing classes public class ClassName { //Data members private int a;
… //Constructor(s) public ClassName //Code of the method } //other methods public return_type method1(type param1, type param2, …)
466
Writing the main() public class MainClassName { //Data members
Static BufferedReader keyboard=…; //main method public static void main(…) //Code of the main method } //other methods public static return_type method1(type param1, …) //Code of the method
467
This is wrong!! No instructions directly in the body of a class!!!
public class ClassName { //Data members private int a; … //Constructor(s) OtherClass obj=new OtherClass(); //other methods public return_type method1(type param1, …) //Code of the method } No instructions directly in the body of a class!!! They have to be inside a method Exception: initialization of a static variable (e.g. keyboard)
468
Review Arrays Declaration can use variables and Instantiation
1 2 3 Review Arrays Declaration int[] counts; Instantiation counts = new int[50]; Initialization / Access for (int i=0; i<counts.length; i++) { counts[i] = 0; } Initializer List declaration, instantiation, and initialization double[] grades = {98.7, 72.4, 87.5}; int[] numbers = {num, num+1, num+2, num+3}; can use variables and expressions as initial values
469
Arrays and Assignment doesn't make a copy of the array!
int[] counter = new int[5]; temp counter int[] temp; 1 2 3 4 temp = counter; doesn't make a copy of the array! temp == counter is true since the reference variables contain the same address
470
Copying Arrays counter int[] counter = {1, 2, 3, 4, 5};
int[] temp = new int[counter.length]; temp 1 2 3 4 1 1 2 3 4 1 2 2 3 3 4 4 5 5 i for (int i=0; i<counter.length; i++) { temp[i] = counter[i]; } 3 5 4 2 1
471
References and Assignment
counter temp = counter; temp 1 2 3 4 1 1 2 3 4 1 2 2 3 3 4 4 5 5 Remember that arrays use reference variables just like objects.
472
References and null temp = null;
null is a reserved word that means "empty/nothing” counter temp = null; temp 1 2 3 4 1 1 2 3 4 1 2 2 3 3 4 4 5 5 Remember that arrays use reference variables just like objects.
473
Arrays as Parameters Entire array can be passed as a parameter
method can change elements of the array permanently since we're passing a reference Elements of an array can be passed as parameters, too normal rules apply…
474
scores[2]: 20 scores[3]: 30 temp : 20 scores[2]: 30 scores[3]: 20
public class Tester { public static void swap (int[] scores, int x, int y) int temp = scores[x]; scores[x] = scores[y]; scores[y] = temp; } public static void main (String[] args) int[] grades = new int[4]; for (int i=0; i<grades.length; i++) { grades[i] = i*10; swap (grades, 2, 3); scores[2]: 20 scores[3]: 30 temp : 20 scores[2]: 30 scores[3]: 20 temp : 20 scores[2]: 30 scores[3]: 30 temp : 20 When we use grades as a parameter to a method, we're passing the address of the integer array. If we change the array using the [] operator, we're actually changing the array "pointed to" by grades. The formal parameter associated with the array is called an "alias", since there are two variables (the actual parameter and the formal parameter) that refer to the same array. BEFORE: grades[2] contains 20, grades[3] contains 30 AFTER: grades[2] contains 30, grades[3] contains 20 grades[2]: 30 grades[3]: 20 grades[2]: 20 grades[3]: 30
475
Arrays of Objects Can use arrays to manipulate objects
Create array of objects Must instantiate each object in array classname[] array = new classname[size]; for(int j=0; j <array.length; j++) { array[j] = new classname(); }
476
Example 16 students Each student: Create arrays of all the data
String name int age String major int year Create arrays of all the data Problem: print the names according to increasing age Analyze: without objects or with objects? Why?
477
To do Homework 6 Objects/classes. Exercise:
Start with requirements 1 and 4. Objects/classes. Exercise: Create classes House and Roommate. House will have an array of Roommates. Create methods to set number of Roommates, etc (whatever you come up with) Test the classes by writing calls to the methods in the main() method Come to discuss problems
478
COMP 14 Introduction to Programming
Adrian Ilie July 19, 2005
479
Today Review arrays Searching arrays for a particular value
Sorting arrays
480
Exercises 1. Find Sum and Average of Array
1 2 3 Exercises 1. Find Sum and Average of Array 2. Determine Largest and Smallest Elements in Array sale is a double array
481
Example Find Sum and Average of Array
1 2 3 Example Find Sum and Average of Array double[] sale={3.5, 4.6, 5.2, 3.8}; double sum = 0; double average; sale is a double array
482
Example Find Sum and Average of Array
1 2 3 Example Find Sum and Average of Array double[] sale={3.5, 4.6, 5.2, 3.8}; double sum = 0; for(int ind = 0; ind < sale.length; ind++) { sum = sum + sale[ind]; } double average; if(sale.length != 0) average = sum / sale.length; else average = 0.0; sale is a double array
483
Example Determining Largest/Smallest Element in Array
1 2 3 Example Determining Largest/Smallest Element in Array double[] sale={3.5, 4.6, 5.2, 3.8}; int maxIndex = 0, minIndex = 0; double largestSale; double smallestSale;
484
Example Determining Largest/Smallest Element in Array
1 2 3 Example Determining Largest/Smallest Element in Array double[] sale={3.5, 4.6, 5.2, 3.8}; int maxIndex = 0, minIndex = 0; for (int ind = 1; ind < sale.length; ind++) { if (sale[ind] > sale[maxIndex]) maxIndex = ind; else if (sale[ind] < sale[minIndex]) minIndex = ind; } double largestSale = sale[maxIndex]; double smallestSale = sale[minIndex];
485
Searching Arrays Find one/several particular element(s) in an array of many elements Complexity (How Long To Search?) find a parking space - linear look up a word in a dictionary - complex 500K+ words in Oxford Dictionary search - very complex over 3 trillion web pages What if we want to look for a particular value in an array? We have to go through the array one element at a time. How long will that take? Depends on the size of the array. What if the array is sorted in numerical order? Could we find the item faster, without having to look at every element?
486
Time Complexity Important feature in Computer Science research:
How long does an algorithm take to complete? Given an input (e.g. an array) of size n, how long does it take for the algorithm (e.g. search for a particular value) to complete? Linear algorithm: time = k1 * n Quadratic algorithm: time = k2 * n2 etc.
487
Linear Searching Algorithm: Inefficient Relatively easy to program
Get a test value and a list of values list can be ordered or unordered loop through the list repeatedly ask: Is this a match? quit when the answer is yes (use break statement) if you finish all items, there is no match Inefficient worst time to search is the length of the list Relatively easy to program
488
Example Linear Search int[] list={3, 6, 27, 8, 33, 54, 23};
1 2 3 Example Linear Search int[] list={3, 6, 27, 8, 33, 54, 23}; int foundAt = -1, element = 33;
489
Example Linear Search int[] list={3, 6, 27, 8, 33, 54, 23};
1 2 3 Example Linear Search int[] list={3, 6, 27, 8, 33, 54, 23}; int foundAt = -1, element = 33; for(int i=0; i<list.length; i++) { if(list[i] == element) foundAt = i; break; } }
490
Array of Objects Declare array of Student objects (ref. variables)
Instantiate array of size 10 Instantiate each of the Student objects Ask for age (int) and name (String) Instantiate object
491
Example Array of Student objects Student[] students;
1 2 3 Example Array of Student objects Student[] students; students = new Student[10]; for(int i = 1; i < students.length; i++) { //get int age //get String name students[i]=new Student(name, age); }
492
Example Search for student Mark int foundAt=-1; String name=“Mark”;
1 2 3 Example Search for student Mark int foundAt=-1; String name=“Mark”; for(int i = 0; i < students.length; i++) { if(students[i].getName().equals(name)) fountAt=i; break; }
493
Binary Search Requires ordered (sorted) list
Set searchRange to the entire list Repeat: pick a “test value” in the middle of searchRange if test value == value searching for Stop! if test value > value searching for searchRange = lower half of searchRange if test value < value searching for searchRange = upper half of searchRange Binary search is a little more intelligent searching
494
Example Trial 1 Looking for 46 2 SearchRange in yellow 3
495
Sorting Sort students by birth date
Get a group of 5 students Another student will sort them by birth date Analyze the sorting strategy Can we devise an algorithm following that strategy? Goal: sort following a methodology We should be able to write it as an algorithm and then program it Demonstrate selection sort Write algorithm
496
Selection Sort General Algorithm
Scan the list to find the smallest value Swap that value with the value in the first position in the list Scan rest of list to find the next smallest value Swap that value with the value in the second position in the list And so on, until you get to the end of the list
497
Selection Sort Methods
Scan the list to find the smallest value Swap that value with the value in the first position in the list Scan rest of list to find the next smallest value Swap that value with the value in the second position in the list And so on, until you get to the end of the list loop
498
Selection Sort Sorts in ascending order
Can be changed to sort in descending order look for max instead of min
499
Homework 6 Read/write files Array of ints Array of Participant objects
Next: Sort array of ints Sort array of participants Extra credit: group participants
500
Tomorrow Java applets HTML GUIs Reading Assignment:
Chapter 6 pp (pp in old book) skim Chapter 13 pp (pp in old book)
501
COMP 14 Introduction to Programming
Adrian Ilie July 20, 2005
502
Last Week of Class Basic programming concepts Java applets Review
Finish assignment 6 Java applets Compose a web page with a Java applet Advance GUI (beyond JOptionPane) HTML
503
Advanced GUI class JFrame class JApplet Methods Concept of Inheritance
Events class JApplet
504
GUIs We used JOptionPane to create a GUI Calculator using dialog boxes. We can create more complex GUIs using Java.
505
Inheritance JFrame is a class provided by the package javax.swing
Instead of instantiating an object of the JFrame class, we're going to extend the JFrame class (called inheritance). The new class "inherits" features (including methods and variables) from the existing class -- big time-saver! We can use all of the methods and variables from JFrame, while adding our own. If you take COMP 114, you'll learn a lot more about inheritance
506
Extending JFrame Use the modifier extends, which is a reserved word
JFrame is the superclass BigGUI is the subclass It is ok to learn the recipe public class BigGUI extends JFrame { }
507
Next Step We'll need a constructor for BigGUI We'll need a main method
set the window title setTitle set the window size setSize set the default operation when the close button is pressed setDefaultCloseOperation display the window setVisible(true) We'll need a main method create an object of the BigGUI class (which will call the constructor)
508
import javax.swing.*; // needed for JFrame public class BigGUI extends JFrame { private final static String TITLE = “Big GUI"; private final static int WIDTH = 700; private final static int HEIGHT = 600; public BigGUI() // constructor { setTitle(TITLE); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { BigGUI gui = new BigGUI(); } } BlackjackUITest1
509
BigGUI.java Create JFrame and test. JFrame content pane
510
Adding Things Access the content pane so we can add things (buttons, labels, images) Container class is provided by the java.awt package add import statement for java.awt Then, we set the layout type and add things to the content pane Container content = getContentPane();
511
Layout Managers FlowLayout BorderLayout GridLayout default
components are added left to right, top to bottom BorderLayout consists of NORTH, SOUTH, EAST, WEST, CENTER regions size of CENTER region depends on the number of components in the EAST and WEST regions GridLayout define number of rows and columns to get equally sized cells cells are filled left to right, top to bottom
512
BorderLayout Select layout for BigGUI as BorderLayout
When adding components with BorderLayout, you have to specify the section (using NORTH, SOUTH, EAST, WEST, CENTER constants from BorderLayout class) content.setLayout(new BorderLayout()); content.add(item, BorderLayout.SECTION);
513
BigGUI.java Get content pane and set layout.
514
JLabels We'll identify the regions of the BorderLayout with labels (text areas) JLabel is a region of text can be assigned an alignment (left-justified, right-justified, centered) Text can be changed with setText method JLabel northLabel = new JLabel ("NORTH", SwingConstants.CENTER); JLabel southLabel = new JLabel ("SOUTH"); northLabel.setText ("Changed Text");
515
Adding Labels Container content = getContentPane(); content.setLayout (new BorderLayout()); JLabel northLabel = new JLabel ("NORTH", SwingConstants.RIGHT); content.add (northLabel, BorderLayout.NORTH); JLabel southLabel = new JLabel ("SOUTH"); content.add (southLabel, BorderLayout.SOUTH); JLabel westLabel = new JLabel ("WEST", SwingConstants.CENTER); content.add (westLabel, BorderLayout.WEST);
516
Adding Labels After adding stuff to the content pane...
setVisible(true);
517
BigGUI.java Add labels.
518
Colors Set the background color of the content pane
Set the foreground color of the text (JLabels) Use Color class from the java.awt package Available colors pg. 734 constants (but lowercase) Methods darker() - darkens the color brighter() - brightens the color content.setBackground(Color.blue.darker().darker()); northLabel.setForeground(Color.white);
519
Adding Images We can create images and associate them with labels
ImageIcon use JPG or GIF images Use setIcon method from JLabel class ImageIcon image = new ImageIcon ("img/0.gif"); filename centerLabel.setIcon (image);
520
Text Position Relative to Icon
label.setVerticalTextPosition(vposition); label.setHorizontalTextPosition(hposition); SwingConstants.TOP SwingConstants.CENTER SwingConstants.BOTTOM SwingConstants.LEFT SwingConstants.CENTER SwingConstants.RIGHT
521
BigGUI.java Add icon.
522
To do Read ch. 6: pp 320-328 (282-290 in old book) - important
Get AFS for web space Homework 6 Homework 7 will be assigned
523
COMP 14 Introduction to Programming
Adrian Ilie July 21, 2005
524
Last Time Create a Java window extending JFrame.
Add labels with JLabel Add Images with ImageIcon Setting colors and layout
525
Example: LowerUpperCase
526
Basics Layout: GridLayout(3,2) JLabel to output result
JTextField to input sentence 4 buttons
527
JLabel and JTextField Very similar. With JTextField we can also type data from outside and access it in the program. JLabel output=new JLabel(); JTextField input=new JTextField(); … String inputStr=input.getText(); output.setText(“OUTPUT RESULT”);
528
Using Buttons Create JButton objects
Buttons generate events when clicked Add event handlers Inside event handler, code operations to be executed when button is clicked
529
Adding Buttons To create a button, we use the JButton class
Add button to the content pane Change text of the button with the setText method Enable/disable the button with setEnabled method JButton toLower = new JButton (“To Lower Case"); content.add(toLower); toLower.setText(“Convert to Lower Case"); toLower.setEnabled(false);
530
Buttons and Events Pressing buttons triggers action events
Setup a listener for the event actionPerformed method from ActionListener class ActionListener class from the java.awt.event package something else to import
531
ActionListener Special type of class, called interface
Interface - class that contains only the method headings (no method bodies) public interface ActionListener { public void actionPerformed (ActionEvent e); }
532
ActionListener In order to handle an event, define a class that will implement ActionListener. Make the class ButtonHandler an internal class of our main class. In ButtonHandler, code the method actionPerformed private class ButtonHandler implements ActionListener
533
ActionListener Declare a ButtonHandler that will be a data member of the main class. Instantiate the ButtonHandler (e.g. in the constructor) Once the JButton object is created, register the action listener: private ButtonHandler toLowerHandler; toLowerHandler=new ButtonHandler(); toLower.addActionListener(toLowerHandler);
534
Example: LowerUpperCase
Declare buttons: toLowerButton, toUpperButton, exitButton, clearButton Instantiate buttons Add buttons to the content pane Implement ActionListener classes that will handle events: ButtonHandler, ExitHandler, ClearHandler Register action listeners
535
actionPerformed Variables we want to access inside the actionPerformed methods, must be declared as member variables of the main class not local to constructor Make input, output, and the buttons member variables
536
ExitHandler.actionPerformed
We simply need to exit the system System.exit(0);
537
ClearHandler.actionPerformed
Clear JTextField input and JLabel output input.setText(“”); output.setText(“”); setVisible(true);
538
ButtonHandler.actionPerformed
How do we know which button we pressed (toLower or toUpper)? public void actionPerformed(ActionEvent e) { JButton pressed=(JButton)(e.getSource()); if(pressed==toLower) … else if(pressed==toUpper) }
539
Example: LowerUpperCase
Finish example
540
Applets A Java application is a stand-alone program with a main method
A Java applet is a Java program that is intended to be transported over the web and executed using a web browser an applet doesn't have a main method needs an extra import statement: import java.applet.Applet;
541
Applet Methods Several methods from Applet class that are invoked automatically at certain points in an applet's life init - executed only once when the applet is initially loaded start - called when applet becomes active (when browser loads / returns to the page) stop - called when applet becomes inactive (when browser leaves the page) paint - automatically executed and is used to draw the applets contents
542
Converting Apps to Applet
See Ch 13, pgs ( ) Extends JApplet instead of JFrame No main method No constructor put code from constructor in init() method No setVisible, setTitle, or setSize methods
543
Example: LowerUpperCase
Convert to Applet
544
Want to Learn More? Creating a GUI with Swing Creating Applets
545
Writing Web Pages Web pages are written in a "markup" language called HTML (HyperText Markup Language) HTML is NOT a programming language. HTML just tells the computer how to format text and images--it's like using Word, but having to type in what you want things to look like.
546
Tags HTML works based on the concept of tags. A tag is some text surrounded by < and > Tags are not printed to the screen Example tags: <HTML>, <TITLE>, <P>, <H1> A lot of the time they work in pairs: <HTML> and </HTML> HTML is not case-sensitive <HTML> and <html> are the same thing
547
Very Simple Web Page <HTML> <HEAD>
<TITLE>Simple web page</TITLE> </HEAD> <BODY> This is the text on a web page. </BODY> </HTML> View any web page source by choosing Source from the View menu in a web browser
548
What Do The Tags Mean? <HTML>, </HTML>
go at the beginning and end of EVERY page <HEAD>, </HEAD> introduction of the document <TITLE>, </TITLE> what goes in the title bar of the window <BODY>,</BODY> the text (and other stuff) that is displayed in the window
549
Color and Images You can add color or an image to the background:
color: make body tag <BODY BGCOLOR=RED> image: make body tag <BODY BACKGROUND="image.gif">
550
Ignores White Space In HTML, where you put a line break is ignored. The web browser decides this for you based on the size of the window These two will print the same thing: first: <BODY> Why not fly? </BODY> second: <BODY> Why not fly? </BODY>
551
Adding White Space Putting <P> at the beginning of a paragraph and </P> at the end will put a blank line between two pieces of text You can also use <BR> to insert a carriage return (aka <enter>) <hr> will insert a horizontal line
552
Other Tags Bold Italic Center Comments <B> and</B>
<I> and </I> Center <CENTER> and </CENTER> Comments <!-- and -->
553
Hierarchical Structure
For documents having a hierarchical structure, you can use heading tags <H1> marking chapter in a book <H2> marking section of a chapter <H3> marking subsection of a chapter <H4> and so on down... <H5>
554
Lists There are two kinds of lists:
Ordered lists (surrounded by <OL> and </OL> Unordered lists (surrounded by <UL> and </UL> Both use <LI> and </LI> to indicate List Items (things in the list)
555
Tables You can also create tables
Beginning: <TABLE> </TABLE> options: border, cellspacing, cellpadding Each row: <TR> </TR> Each column: <TD> </TD>
556
Links This is the important part. This is how you go from page to page. <A HREF="put URL here">text to be displayed</A>
557
Inserting Images You can also just add an image into the middle of the page Use <IMG SRC="put URL here">
558
Want To Learn More? Tutorials Quick Reference
559
Applets and the Web An applet is embedded into an HTML file using a tag that references the bytecode file (ClassName.class) of the applet class It is actually the bytecode version of the program that is transported across the web The applet is executed by a Java interpreter that is part of the browser this Java interpreter not included in Windows XP, must download from java.com
560
Applets and the Web Basic HTML file for an applet:
Can also specify size of applet window Put the applet HTML file (named something.html) and your Java applet bytecode (named ClassName.class) in your public_html folder in AFS space. <html> <body> <applet code = "ClassName.class"> </applet> </body> </html> <applet code="ClassName.class" height=200 width=300> </applet> The whole idea behind applets was to be able to run a program over the web
561
To do Finish Homework 6 (due Saturday night)
Sort ints Create array of Participant objects Read data into Participant objects Sort Participant objects Start Homework 7 (due Monday night) Access AFS disk space Create simple web page (just one line in the body) Play around with UpperLower.java Bring laptops to the remaining classes (review & practice)
562
COMP 14 Introduction to Programming
Adrian Ilie - COMP 14 - Summer 2005 COMP 14 Introduction to Programming Adrian Ilie Summer Session II, 2005 MTWRF 9:45-11:15 am Sitterson Hall 011
563
Adrian Ilie - COMP 14 - Summer 2005
Grades Assignments (7) 45% Quizzes (3) 10% Midterm 15% Final/Project 25% Class participation 5%
564
Adrian Ilie - COMP 14 - Summer 2005
Exams Midterm to take a make-up midterm, you must notify me in advance or have a doctor's excuse Final to take the exam at a different time, you must get permission from your Dean and bring me the blue slip you get from the Dean
565
Adrian Ilie - COMP 14 - Summer 2005
Hardware vs. Software A computer is made up of hardware and software Hardware Software CPU ex: 2 GHz Pentium IV input/output keyboard monitor network card main memory ex: 256 MB RAM secondary memory ex: 20 GB hard drive operating systems Windows XP Mac OS X applications games Microsoft Word Internet Explorer
566
Hardware Organization
Adrian Ilie - COMP 14 - Summer 2005 Hardware Organization CPU memory motherboard hard drive
567
Central Processing Unit
Adrian Ilie - COMP 14 - Summer 2005 Central Processing Unit Control Unit (CU) "the brain" of the CPU Program Counter (PC) points to the next instruction to be executed Instruction Register (IR) holds the currently executing instruction Arithmetic Logic Unit (ALU) carries out all arithmetic and logical ops Accumulator (ACC) holds the results of the operations performed by the ALU CU fetch and decode instructions control the flow of info between CPU and main memory control the operation of the other CPU components
568
Adrian Ilie - COMP 14 - Summer 2005
Main Memory Ordered sequence of cells AKA Random Access Memory (RAM) Directly connected to the CPU All programs must be brought into main memory before execution When power is turned off, everything in main memory is lost
569
Adrian Ilie - COMP 14 - Summer 2005
Secondary Storage Provides permanent storage for information Retains information even when power is off Examples of secondary storage: Hard Disks Floppy Disks ZIP Disks CD-ROMs Tapes
570
Adrian Ilie - COMP 14 - Summer 2005
Input Devices Definition: devices that feed data and computer programs into computers Examples: Keyboard Mouse Secondary Storage
571
Adrian Ilie - COMP 14 - Summer 2005
Output Devices Definition: devices that the computer uses to display results Examples: Printer Monitor Secondary Storage
572
Adrian Ilie - COMP 14 - Summer 2005
Input/Output Devices I/O devices facilitate user interaction
573
Adrian Ilie - COMP 14 - Summer 2005
Hardware Components
574
Adrian Ilie - COMP 14 - Summer 2005
Opening MS Word Use the mouse to select MS Word The CPU requests the MS Word application MS Word is loaded from the hard drive to main memory The CPU reads instructions from main memory and executes them one at a time MS Word is displayed on your monitor
575
Adrian Ilie - COMP 14 - Summer 2005
Software Categories Operating System controls all machine activities provides the user interface to the computer first program to load when a computer is turned on manages computer resources, such as the CPU, memory, and hard drive examples: Windows XP, Linux, Mac OS X Application generic term for any other kind of software examples: word processors, missile control systems, games
576
Adrian Ilie - COMP 14 - Summer 2005
Operating System (OS) OS monitors overall activity of the computer and provides services Written using programming language Example services: memory management input/output storage management
577
Adrian Ilie - COMP 14 - Summer 2005
Application Programs Written using programming languages Perform a specific task Run by the OS Example programs: Word Processors Spreadsheets Games
578
Adrian Ilie - COMP 14 - Summer 2005
Binary Numbers N bits to represent 2N values N bits represent values 0 to 2N-1 Example: 5 bits 32 unique values (0-31) = 010 = 3110 = 31
579
Converting Decimal to Binary
Let’s convert 114 to binary Repeatedly divide by 2 and write down the remainder: 114/2=57 remainder 0 57/2=28 remainder 1 28/2=14 remainder 0 14/2=7 remainder 0 7/2=3 remainder 1 3/2=1 remainder 1 1/2=0 remainder 1 Write the remainders in reverse order: =11410 Proof – rewrite and add the equations above: 114=(((((((1*2)+1)*2+1)*2+0)*2+0)*2+1)*2+0)= =1*26+1*25+1*24+0*23+0*22+1*21+0*20
580
Programming Languages
Adrian Ilie - COMP 14 - Summer 2005 Programming Languages High-level languages make programming easier Closer to spoken languages Examples: Basic FORTRAN COBOL C/C++ Java
581
Java and Machine Language
To run a Java program: Java instructions need to be translated into an intermediate language called bytecode. The bytecode is interpreted into a particular machine language.
582
Compiler Compiler: A program that translates a program written in a high-level language into the equivalent machine language. (In the case of Java, this machine language is the bytecode.) Java Virtual Machine (JVM): A hypothetical computer developed to make Java programs machine independent.
583
Processing a Java Program
Program: written in Java using the Editor and compiled to Bytecode using the Compiler. Loader: transfers the compiled code (bytecode) into main memory and loads the necessary Libraries. Interpreter: reads and translates each bytecode instruction into machine language and then executes it.
584
Adrian Ilie - COMP 14 - Summer 2005
Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: understand the problem dissect the problem into manageable pieces design a solution consider alternatives to the solution and refine it implement the solution test the solution and fix any problems that exist
585
Adrian Ilie - COMP 14 - Summer 2005
Algorithm Sequence of instructions used to carry out a task or solve a problem May be written in either English or pseudocode outline of a program that could be translated into actual code May need refinement as you work Always write out your algorithm before you begin programming
586
Problem-Analysis-Coding-Execution
Adrian Ilie - COMP 14 - Summer 2005 Problem-Analysis-Coding-Execution most important step without computer with computer
587
Algorithm Design Example
Adrian Ilie - COMP 14 - Summer 2005 Algorithm Design Example Problem: Convert change in cents to number of half-dollars, quarters, dimes, nickels, and pennies to be returned. Example: given 646 cents number of half-dollars: divide 646 by 50 quotient is 12 (number of half-dollars) remainder is 46 (change left over) number of quarters: divide 46 by 25 quotient is 1 (number of quarters) remainder is 21 (change left over) number of dimes, nickels, pennies result: 12 half-dollars, 1 quarter, 2 dimes, 0 nickels, 1 penny
588
Adrian Ilie - COMP 14 - Summer 2005
Resulting Algorithm Get the change in cents Find the number of half-dollars Calculate the remaining change Find the number of quarters Find the number of dimes Find the number of nickels The remaining change is the number of pennies.
589
Programming Languages
Adrian Ilie - COMP 14 - Summer 2005 Programming Languages Programming languages have rules of grammar just as English does syntax rules - which statements are legal and which are not semantic rules - determine the meaning of the instructions token - smallest individual unit of a program special symbols word symbols identifiers
590
Adrian Ilie - COMP 14 - Summer 2005
Special Symbols + - * / . ; ? , <= != == >= the 3rd row contains two characters that together (with no space between them) are considered to be a single symbol
591
Word Symbols aka reserved words, or keywords
Adrian Ilie - COMP 14 - Summer 2005 Word Symbols aka reserved words, or keywords int float double char void public static throws return reserved words are always all lowercase each word symbol is considered to be a single symbol cannot be used for anything other than their intended purpose in a program shown in blue typewriter font in textbook full table in Appendix A
592
Adrian Ilie - COMP 14 - Summer 2005
Identifiers Names of things (variables, constants, methods) in your programs Can be composed of any combination of letters, digits, underscore (_), and dollar sign ($) Cannot begin with a digit May be any length Java is case-sensitive Total, total, and TOTAL are different identifiers
593
Adrian Ilie - COMP 14 - Summer 2005
Primitive Data Types 8 primitive data types in Java 4 represent integers byte, short, int, long 2 represent floating point numbers float, double 1 represents characters char 1 represents boolean values boolean
594
Arithmetic Expressions
Adrian Ilie - COMP 14 - Summer 2005 Arithmetic Expressions Expression - a combination of one or more operands and their operators Arithmetic expressions compute numeric results and make use of the arithmetic operators: If either or both operands associated with an arithmetic operator are floating point, the result is a floating point Addition + Subtraction - Multiplication * Division / Remainder %
595
Adrian Ilie - COMP 14 - Summer 2005
Operator Precedence Determines the order in which operators are evaluated: multiplication, division, and remainder addition, subtraction, and string concatenation arithmetic operators with the same precedence are evaluated from left to right Parentheses can be used to force the evaluation order (just like in math)
596
Type Conversion (Casting)
Adrian Ilie - COMP 14 - Summer 2005 Type Conversion (Casting) Used to avoid implicit type coercion Syntax (dataTypeName) expression Expression evaluated first, then type converted to dataTypeName Examples: (int) ( ) = 14 (int) (7.9) + (int)(6.7) = 13 casting a floating-point number to an integer truncates everything after the decimal point (int) 14.6 7 + 6 the textbook has very nice examples of mixed expressions and casting on pgs make sure you take a look at them and understand the answers
597
Adrian Ilie - COMP 14 - Summer 2005
The class String String sequence of zero or more characters enclosed in double quotation marks null or empty strings have no characters numeric strings consist of integers or decimal numbers length is the number of characters in a string The class String is used to manipulate strings Examples: "Hello World" "1234" "45.67" "" note the null, or empty, string
598
Adrian Ilie - COMP 14 - Summer 2005
Strings Every character has a position in the string (starting with 0) "Hello World" The length of the string is the number of characters in it what's the length of "Hello World"? 11 (count the space)
599
Parsing Numeric Strings
Adrian Ilie - COMP 14 - Summer 2005 Parsing Numeric Strings In Java, input from the user comes in the form of a string we need to know how to get the number values out of the string Numeric String a string with only integers or decimal numbers "6723", "-823", "345.76"
600
Adrian Ilie - COMP 14 - Summer 2005
Variables Associated with data Input data Output data Intermediate data We need to define: Data type Identifier Values will be assigned in expressions Start by learning how to declare variables Variables are associated with data
601
Adrian Ilie - COMP 14 - Summer 2005
Variables - Steps Identify all data from the algorithm Determine data types (based on the range and nature of the values) Find meaningful names Example: Ch. 1, Exercise 10. Compute average score.
602
Declaration of Variables
Adrian Ilie - COMP 14 - Summer 2005 Declaration of Variables dataType identifier; Must be declared before it can be used Can be (but doesn't have to be) initialized when declared Identifier should start in lowercase, indicate separate words with uppercase (good style) Example: number of students in class int numStudents; Multiple variables (of the same data type) can be declared on a single line int numStudents, numGrades, total;
603
Adrian Ilie - COMP 14 - Summer 2005
Assignment variable = expresssion; Assignment Operator (=) expression can be a value (3) or a mathematical expression (2 + 1) The expression must evaluate to the same data type as the variable was declared
604
Adrian Ilie - COMP 14 - Summer 2005
Named Constant static final dataType IDENTIFIER = value; Declared by using the reserved word final Always initialized when it is declared Identifier should be in ALL CAPS, separate words with underscore (_) (good style) Example: 1 inch is always 2.54 centimeters final double CM_PER_INCH = 2.54; static is optional (we'll talk about when you have to use it next week) initialized -- given some initial value the compiler will give an error if you try to change the value of a constant after it's been declared and initialized
605
Adrian Ilie - COMP 14 - Summer 2005
Input Standard input BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in)); String line = keyboard.readLine(); Dialog windows str = JOptionPane.showInputDialog(strExpression); File BufferedReader inFile = new BufferedReader (new FileReader (file)); String line = inFile.readLine(); inFile.close(); We’re going to study 3 ways to input variables to the program.
606
Adrian Ilie - COMP 14 - Summer 2005
Output Standard output System.out.print<ln>(string) Dialog boxes JOptionPane.showMessageDialog(parentComponent, strExpression,boxTitleString,messageType); File String file = "outfile.dat"; PrintWriter outFile = new PrintWriter (new FileWriter (file)); outFile.print ("Hi"); outFile.println(" There!"); outFile.close(); We've talked about how to get input from the user. Now, how do we print things out to the user?
607
Writing a Whole Program
Adrian Ilie - COMP 14 - Summer 2005 Writing a Whole Program Class - used to group a set of related operations (methods), allows users to create their own data types Method - set of instructions designed to accomplish a specific task Package - collection of related classes Library - collection of packages
608
Adrian Ilie - COMP 14 - Summer 2005
Class Libraries A collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment The System class and the String class are part of the Java standard class library The Java standard class library classes are not part of the Java language itself, but we rely on them heavily.
609
Adrian Ilie - COMP 14 - Summer 2005
Packages The classes of the Java standard class library are organized into packages. Some of the packages in the standard class library are: Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities XML document processing We’ll talk about how to use these next...
610
Adrian Ilie - COMP 14 - Summer 2005
Using Packages We need to import some of the packages we want to use java.io for BufferedReader import packageName; import java.io.*; imports all of the classes in the java.io package import java.io.BufferedReader; imports only the BufferedReader class from the java.io package
611
Using Predefined Classes and Methods
Adrian Ilie - COMP 14 - Summer 2005 Using Predefined Classes and Methods To use a method you must know: Name of class containing method (Math) Name of package containing class (java.lang) Name of method (round), its parameters (double a), what it returns (long), and function (rounds a to the nearest integer) See Appendix E for more Java predefined classes
612
Creating a Java Program
Adrian Ilie - COMP 14 - Summer 2005 Creating a Java Program Java application program - collection of one or more classes every application must have at least one class Class basic unit of a Java program collection of methods and data members Method - set of instructions designed to accomplish a specific task print, readLine
613
Adrian Ilie - COMP 14 - Summer 2005
Programming in Java Java programming language object-oriented approach to problem solving In the Java programming language: a program is made up of one or more classes a class contains one or more methods a method contains program statements
614
Creating a Java Program
Adrian Ilie - COMP 14 - Summer 2005 Creating a Java Program All Java application programs must have a method called main there can be only one main method in any Java application program Most of the time, our programs will have only one class Name of source file must be ClassNameWithMain.java
615
Adrian Ilie - COMP 14 - Summer 2005
Throws Clause throws clause - exceptions thrown by the main method exception - occurrence of an undesirable situation that can be detected during program execution can either be handled or thrown readLine throws the exception IOException We won't handle the exception, we'll just throw it
616
Adrian Ilie - COMP 14 - Summer 2005
Import Statements Tell the compiler which packages are used in the program Import statements and program statements constitute the source code Source code saved in a file with the extension .java Source code file must have the same name as the class with the main method
617
Adrian Ilie - COMP 14 - Summer 2005
The main method Heading Body statements enclosed by { } declaration statements used to declare things such as variables executable statements perform calculations, manipulate data, create output, accept input, etc. public static void main (String[] args) throws IOException
618
Adrian Ilie - COMP 14 - Summer 2005
Skeleton import statements if any public class ClassName { declare named constants and/or stream objects public static void main (String[] args) throws IOException variable declarations executable statements }
619
Adrian Ilie - COMP 14 - Summer 2005
Style Syntax beware! a syntax error in one place might lead to syntax errors in several other places Use of semicolons, braces, commas all Java statements end with semicolon braces {} enclose the body of a method and set it off from other parts of the program (also have other uses) commas separate list items
620
Adrian Ilie - COMP 14 - Summer 2005
Style Semantics set of rules that gives meaning to a language beware! the compiler will not be able to tell you about semantic errors (example: missing parentheses in mathematical expression) Documentation comments naming rules use meaningful identifiers prompt lines let the user know what type of input is expected
621
Adrian Ilie - COMP 14 - Summer 2005
Style and White Space White space blanks, tabs, blank lines used to separate words and symbols extra space is ignored by computer blank line between variable declaration and rest of code Programs should be formatted to enhance readability, using consistent indentation
622
Adrian Ilie - COMP 14 - Summer 2005
Comments Not used by the computer only for human consumption Used to help others understand code explain and show steps in algorithm comments are essential! Should be well-written and clear Comment while coding Also called inline documentation
623
Adrian Ilie - COMP 14 - Summer 2005
Java Comments // this is a one-line comment “comments out” the rest of the line after marker // /* this is a multi-line comment */ “comments out” everything between markers /* and */
624
Adrian Ilie - COMP 14 - Summer 2005
Classes What is a class? Data Operations Classes allow creation of new data types public class Student { }
625
Adrian Ilie - COMP 14 - Summer 2005
Classes Vs. Data Types Abstract Descriptors Data Type Class Concrete Entities Variable Object
626
Adrian Ilie - COMP 14 - Summer 2005
Inside a class Other classes Data types Methods (operations) public class Student { private String name; private int age; public void ComputeGrade(); }
627
Adrian Ilie - COMP 14 - Summer 2005
Primitive Variables int x = 45; x is associated with a memory location. It stores the value 45 When the computer sees x, it knows which memory location to look up the value in Remember that a variable is just a name we give for a memory location. When we declare a variable of a primitive data type (int, double, char...), memory for that data type is reserved, and the address of the data is associated with the variable.
628
Adrian Ilie - COMP 14 - Summer 2005
Reference Variables Integer num; The memory location associated with num can store a memory address. The computer will read the address in num and look up an Integer object in that memory location Just like we can declare an int, we can declare an Integer variable. Note that we haven't yet created an object, we've just created a placeholder for the address for the object.
629
Adrian Ilie - COMP 14 - Summer 2005
Creating Objects We use the new operator to create objects, called instantiation Integer num; num = new Integer(78); parameter The first line creates a reference variable. The second line creates the Integer object, initializes the Integer value, and stores the address where the object was created in num an object is an instance of a particular class
630
Changing the Reference Var
Adrian Ilie - COMP 14 - Summer 2005 Changing the Reference Var num = new Integer (50); The address of the newly-created object is stored in the already-created reference variable num How would you change the value in the Integer object from 78 to 50? The Integer class doesn't provide a method for changing the value. We could create a new Integer object that stored 50.
631
Adrian Ilie - COMP 14 - Summer 2005
Garbage Collection What happened to the memory space that held the value 78? If no other reference variable points to that object, Java will "throw it away" This is just another way of looking at the previous figure. We say that the reference variable num "points to" the Integer object that contains the value 50.
632
Adrian Ilie - COMP 14 - Summer 2005
Using Objects System.out object represents a destination to which we can send output Example: println method System.out.println (”Hello World!”); object information provided to the method (parameters) method dot operator
633
Adrian Ilie - COMP 14 - Summer 2005
The class String String variables are reference variables Given String name; Equivalent Statements: name = new String(“Van Helsing”); name = “Van Helsing”;
634
Adrian Ilie - COMP 14 - Summer 2005
name = “Van Helsing”; Van Helsing Van Helsing Van Helsing
635
Adrian Ilie - COMP 14 - Summer 2005
The class String The String object is an instance of class string The value “Van Helsing” is instantiated The address of the value is stored in name The new operator is unnecessary when instantiating Java strings String methods are called using the dot operator
636
Adrian Ilie - COMP 14 - Summer 2005
Common String Methods String(String str) constructor creates and initializes the object char charAt(int index) returns char at the position specified by index (starts at 0) int indexOf(char ch) returns the index of the first occurrence of ch int compareTo(String str) returns negative if this string is less than str returns 0 if this string is the same as str returns positive if this string is greater than str All String class methods are in Appendix E (pgs )
637
Adrian Ilie - COMP 14 - Summer 2005
Common String Methods boolean equals(String str) returns true if this string equals str int length() returns the length of the string String replace(char toBeReplaced, char replacedWith) returns the string in which every occurrence of toBeReplaced is replaced with replacedWith String toLowerCase() returns the string that is the the same as this string, but all lower case String toUpperCase() returns the string that is the same as this string, but all upper case
638
The StringTokenizer Class
Adrian Ilie - COMP 14 - Summer 2005 The StringTokenizer Class tokens elements that comprise a string tokenizing process of extracting these elements delimiters characters that separate one token from another StringTokenizer class defined in the java.util package used to separate a string into tokens
639
The StringTokenizer Class
Adrian Ilie - COMP 14 - Summer 2005 The StringTokenizer Class Default delimiters: space, tab, carriage return, new line Methods StringTokenizer (String str) StringTokenizer (String str, String delimits) String nextToken() boolean hasMoreTokens() int countTokens() Note that the first two are called constructors -- they have the same name as the class countTokens -- returns the number of tokens left in the String
640
Adrian Ilie - COMP 14 - Summer 2005
class DecimalFormat Import package java.text Create DecimalFormat object and initialize DecimalFormat fmt = new DecimalFormat (formatString); FormatString "0.00" - limit to 2 decimal places, use 0 if there's no item in that position "0.##" - limit to 2 decimal places, no trailing 0 Use method format rounds the number instead of truncating Result of using DecimalFormat is a String
641
Adrian Ilie - COMP 14 - Summer 2005
Control Structures Three methods of processing a program: In sequence statements are executed one after another in order Branching altering the flow of program execution by making a selection or choice Looping altering the flow of program execution by repetition of statement(s) selection - program executes particular statements depending on some conditions repetition - program repeats particular statements a certain number of times depending on some condition
642
Flow of Execution
643
Adrian Ilie - COMP 14 - Summer 2005
Relational Operators Relational Operator allows you to make comparisons in a program binary operator needs two operands Condition is represented by a logical (Boolean) expression expression that has a value of either true or false To make decisions, you need to be able to make comparisons
644
Adrian Ilie - COMP 14 - Summer 2005
Relational Operators Less than < Greater than > Equal to == not assignment ‘=‘ Not equal to != Less than or equal to <= Greater than or equal to >=
645
Adrian Ilie - COMP 14 - Summer 2005
Comparing Characters In Java, characters are ordered according to the Unicode / ASCII character set (pg. 855) ‘a’ comes before ‘b’ in the character set, so we can say ‘a’ < ‘b’ Order space character (' ') digits (‘0’, ‘1’, …) uppercase lowercase Application: sort alphabetically Makes it easy to alphabetize (just do compares)
646
Comparing Floating-Point
Adrian Ilie - COMP 14 - Summer 2005 Comparing Floating-Point Be careful when using the equality (==) to compare floating point numbers Every bit in the representation must be equal computer can only store a certain number of digits after the decimal If the numbers are results of computation, it’s unlikely that two floating point numbers will be exactly equal
647
Adrian Ilie - COMP 14 - Summer 2005
Comparing Strings Strings are compared on a character-by-character basis first character not in common determines how the strings compare ex: "Airplane" is less than "Airport" If two strings have different lengths, and one is a substring of the other, the shorter one is evaluated as less ex: "Air" is less than "Airplane"
648
Comparing Strings Don't use relational operators (==, <, >)
for Strings str1.compareTo (str2) Returns an integer value: < 0 if str1 is less than str2 0 if str1 is equal to str2 >0 if str1 is greater than str2 str1.equals (str2) Returns a boolean value of true or false method parameter
649
Adrian Ilie - COMP 14 - Summer 2005
Boolean Operators NOT ! (unary) !(2+2==5) AND && (binary) (2+2==5) && (1+1==2) OR || (binary) (2+2==5) || (1+1==2) true false true
650
Short Circuited Operators
Adrian Ilie - COMP 14 - Summer 2005 Short Circuited Operators The processing of logical AND (&&) and logical OR (||) is “short-circuited” If the left operand is sufficient to determine the result, the right operand is not evaluated Be careful when counting on this type of processing count != 0 && (total/count > MAX)
651
Precedence of Operators
652
Adrian Ilie - COMP 14 - Summer 2005
The if Statement The condition must be a boolean expression. It must evaluate to either true or false. if is a Java reserved word if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.
653
Adrian Ilie - COMP 14 - Summer 2005
The if-else Statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed An else clause can be added to an if statement to make an if-else statement Remember that if we used curly braces, we could replace statement1 and statement 2 with block1 and block2 One or the other will be executed, but not both
654
Adrian Ilie - COMP 14 - Summer 2005
Nested if Statements The general syntax of a nested if statement is: if (condition1) { block1 } else if (condition2) block2 else block3
655
Adrian Ilie - COMP 14 - Summer 2005
The switch Statement The general syntax of a switch statement is: switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ... } switch and case are reserved words Don't need braces in the statement list If expression matches value2, control jumps to here
656
Adrian Ilie - COMP 14 - Summer 2005
The switch Statement Expression evaluated must be integral type integer or character, not boolean or floating point Case values must be constant (literal), not variable Can be implemented with nested if statements, but is much clearer with switch statements
657
Adrian Ilie - COMP 14 - Summer 2005
The switch Statement default no case value matches the expression if no default exists and no case value matches the expression, no statements in the switch statement are executed break processing jumps to statement following the switch statement usually at the end of each case Once inside a case, processing continues in order until a break statement is reached
658
Writing Selection Statements What Type of Construct To Use?
Adrian Ilie - COMP 14 - Summer 2005 Writing Selection Statements What Type of Construct To Use? Only need to execute additional statements if condition is true Need to execute separate additional statements based on if the condition is true or false Need to execute different statements based on multiple conditions Need to execute different statements based on an expression that evaluates to a char or int if if-else nested if-else switch
659
Writing Selection Statements
Adrian Ilie - COMP 14 - Summer 2005 Writing Selection Statements Write the outline of the selection statement keywords curly braces case and break statements (for switch) Write the expression boolean expression, or condition expression or variable evaluating to char or int Write statements that execute based on the condition
660
Repetition Statements
Adrian Ilie - COMP 14 - Summer 2005 Repetition Statements Allow us to execute a statement multiple times Often referred to as loops Controlled by boolean expressions like selection, or conditional, statements Java has three kinds of repetition statements: the while loop the for loop the do loop
661
Adrian Ilie - COMP 14 - Summer 2005
Loops Must use a loop control variable controls how many times to loop 4 Parts to Every Loop initialization - set loop control variable before condition condition - when to stop update - change the loop control variable body - actions to repeat
662
Adrian Ilie - COMP 14 - Summer 2005
Typical Uses of Loops Repeat a section of code a specified number of times - counter-controlled Repeat a section of code (reading input) until a specific value is read - sentinel-controlled Repeat a section of code (reading input) until a valid value is entered - input validation Repeat a section of code (reading from a file) until the end of the file is reached - EOF-controlled Repeat a section of code until a boolean variable becomes false - flag-controlled
663
Adrian Ilie - COMP 14 - Summer 2005
The while Loop Syntax while ( condition ) { loop body; } while is a reserved word If the condition is true, the loop body is executed. Then the condition is evaluated again. The loop body is executed repeatedly until the condition becomes false.
664
Adrian Ilie - COMP 14 - Summer 2005
The while Loop Syntax while (expression) statement Expression is always true in an infinite loop Statements must change value of expression to false
665
Counter-Controlled while Loop
Adrian Ilie - COMP 14 - Summer 2005 Counter-Controlled while Loop Used when we know exactly the number of times to execute the loop Basic Form: counter = 0; while (counter < N) { ... counter++; } N is the number of times the loop should execute
666
Sentinel-Controlled while Loop
Adrian Ilie - COMP 14 - Summer 2005 Sentinel-Controlled while Loop Used when exact number of entry pieces is unknown but last entry (special / sentinel value) is known Basic Form: input the first data item into variable while (variable != sentinel) { ... input a data item into variable }
667
Input Validation while Loop
Adrian Ilie - COMP 14 - Summer 2005 Input Validation while Loop Used to ensure that the user enters valid input Basic Form: input a data item into variable while (variable is not in valid range) { ask the user for valid input }
668
Flag-Controlled while Loop
Adrian Ilie - COMP 14 - Summer 2005 Flag-Controlled while Loop Boolean value used to control loop Basic Form: boolean found = false; while (!found) { ... if(expression) found = true; }
669
EOF-Controlled while Loop
Adrian Ilie - COMP 14 - Summer 2005 EOF-Controlled while Loop Used when input is from a file Sentinel value is not always appropriate Basic Form: inputLine = inFile.readLine(); while (inputLine != null) { ... } Assume that inFile is a BufferedReader object that reads input from a file null is a reserved word
670
Adrian Ilie - COMP 14 - Summer 2005
The for Loop Specialized form of while loop Simplifies the writing of count-controlled loops Basic Form: for (initialization; condition; update) { statement(s); }
671
Adrian Ilie - COMP 14 - Summer 2005
The for Loop Execution initial statement executes loop condition evaluated If loop condition evaluates to true, execute for loop statement and execute update statement Go back to step 2 and repeat until loop condition is false
672
Adrian Ilie - COMP 14 - Summer 2005
The for Loop Syntax The initialization is executed once before the loop begins The loop body is executed until the condition becomes false Reserved word for ( initialization; condition; update ) { loop body; } The update portion is executed at the end of each iteration The condition-loop body-update cycle is executed repeatedly
673
Adrian Ilie - COMP 14 - Summer 2005
for vs. while A for loop is functionally equivalent to the following while loop structure: initialization; while ( condition ) { loop body; update; } In a while loop, the update is part of the loop body In a for loop, it's on the outside of the loop body
674
Comparing while and for
Adrian Ilie - COMP 14 - Summer 2005 Comparing while and for While Loop final int LIMIT=3; int i = 0; while (i < LIMIT) { System.out.println (i); i++; } System.out.println (“All done!”); For Loop final int LIMIT=3; int i; for (i=0; i<LIMIT; i++) { System.out.println (i); } System.out.println ("All done!"); for loop is interesting because it might be more efficient on some CPUs
675
Adrian Ilie - COMP 14 - Summer 2005
Watch out! for statement ending in semicolon is empty; does not affect program while statement ending in semicolon results in infinite loop for (count=0; count<LIMIT; count++); while (count<LIMIT);
676
The do...while Loop Syntax
Adrian Ilie - COMP 14 - Summer 2005 The do...while Loop Syntax do { loop body; } while ( condition ); do and while are reserved words The loop body is executed once initially, and then the condition is evaluated Notice the semicolon at the end of the while line The loop body is executed repeatedly until the condition becomes false
677
do…while Loop (Post-test Loop)
Adrian Ilie - COMP 14 - Summer 2005 do…while Loop (Post-test Loop) do { statement(s); } while (expression);
678
Adrian Ilie - COMP 14 - Summer 2005
The do...while Loop Like a while loop, but its condition is at the end of the loop Loop body always executes at least once Must also be checked for termination (not an infinite loop) Anything you can do with a do...while loop, you can do with a while loop
679
Comparing while and do...while
Adrian Ilie - COMP 14 - Summer 2005 Comparing while and do...while while Loop final int LIMIT=3; int count = 0; while (count < LIMIT) { System.out.println (count); count++; } System.out.println (“All done!”); do...while Loop final int LIMIT=3; int count = 0; do { System.out.println (count); count++; } while (count < LIMIT); ("All done!");
680
Adrian Ilie - COMP 14 - Summer 2005
break Statements Used to exit early from a loop Used to skip remainder of switch structure Can be placed within if statement of a loop If condition is met, loop exited immediately
681
Adrian Ilie - COMP 14 - Summer 2005
continue Statements Used in while, for, and do...while structures When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop When executed in a while/do…while structure, expression evaluated immediately after continue statement In a for structure, the update statement is executed after the continue statement; then the loop condition executes
682
Nested Control Structures
Adrian Ilie - COMP 14 - Summer 2005 Nested Control Structures Provides new power, subtlety, and complexity if, if…else, and switch structures can be placed within while loops for loops can be found within other for loops each time through the outer loop, the inner loop goes through its full set of iterations
683
Object-Oriented Design
Adrian Ilie - COMP 14 - Summer 2005 Object-Oriented Design What is it? Designing a solution to a problem by first identifying components called objects, and determining how the objects interact with each other
684
Adrian Ilie - COMP 14 - Summer 2005
Objects VCR Example Use it without knowing how it's made Internal parts are hidden -- only interact with the provided buttons Can't modify the functions of a VCR -- record button always records, play button always plays Same is true for objects (like Strings) that are provided by Java
685
Adrian Ilie - COMP 14 - Summer 2005
Objects Consist of data and operations on the data Data - descriptive characteristics Operations - what it can do (or what can be done to it) Example A coin that can be flipped so that its face shows either "heads" or "tails" data: its current face (heads or tails) operations: it can be flipped Operations can change data.
686
Objects And Methods and Classes
Adrian Ilie - COMP 14 - Summer 2005 Objects And Methods and Classes We represent operations with methods group of statements that are given a name We can use objects and their methods without knowing exactly how the methods work An object is an instance of a class. A class is the blueprint of an object. the class provides the methods that can operate on an object of that class
687
Adrian Ilie - COMP 14 - Summer 2005
Classes A class contains data declarations and method declarations A class is a description of an object just a model, not an actual object you can think of the concept of a book without thinking of a particular book A class is no more an object than a blueprint is an actual house
688
Object-Oriented Design Simplified Methodology
Adrian Ilie - COMP 14 - Summer 2005 Object-Oriented Design Simplified Methodology Write down detailed description of problem Identify all (relevant) nouns and verbs From list of nouns, select objects Identify data components of each object From list of verbs, select operations
689
Adrian Ilie - COMP 14 - Summer 2005
Anatomy of a Class A class contains data declarations and method declarations int width; int length; Data declarations All methods belong to a particular class and operate (or access) objects of that class The data and methods of a class are called its members Method declarations (operations)
690
Adrian Ilie - COMP 14 - Summer 2005
Classes and Objects A class (the concept) An object (the realization) length = 15, width = 3 Rectangle length = 20, width = 6 Multiple objects from the same class length = 15, width = 15
691
Adrian Ilie - COMP 14 - Summer 2005
Why Use Methods? To divide complex programs into manageable pieces Abstraction provide an operation to be performed on an object (ex: computeArea) Code Re-use write a small piece of code that can be used (called) multiple times (saves typing)
692
Adrian Ilie - COMP 14 - Summer 2005
Methods Pre-defined methods provided by Java standard library we've used these before Math class (Math.pow, Math.sqrt, ...) Integer class (Integer.parseInt, ...) User-defined methods you write these
693
Adrian Ilie - COMP 14 - Summer 2005
Method as a Black Box METHOD Input parameters Return value Internal data members of the class A method can use input parameters and internal data members of the class It may modify the value of internal data members It may also return a value
694
Adrian Ilie - COMP 14 - Summer 2005
Control Flow Program control flow execution always begins with the first statement in the method main other methods execute only when called Method control flow when a method is invoked, the flow of control jumps to the method and the computer executes its code when complete, the flow of control returns to the place where the method was called and the computer continues executing code Test this with the debugger!
695
Using Methods What You Need To Know
Adrian Ilie - COMP 14 - Summer 2005 Using Methods What You Need To Know Name of the method Number of parameters Data type of each parameter Data type of value computed (returned) by the method The code required to accomplish the task
696
Adrian Ilie - COMP 14 - Summer 2005
Method Declaration Specifies the code that will be executed when the method is invoked (or called) Located inside a class definition Contains method header method body
697
Adrian Ilie - COMP 14 - Summer 2005
Method Header A method declaration begins with a method header public static int countCharInWord (char ch, String word) visibility modifiers method name formal parameter list return type visibility modifiers -- public if this method can be used (called) from outside the current class/file, private otherwise static -- means that although this method belongs to a class, we don't need to use any member variables in the method body we'll use public and static (like main) for now and talk about when to use private next week return type -- what data type will be returned from the method method name -- naming convention (verbs, start w/lowercase, new words start uppercase) The formal argument list contains the type and name of the variables. These variables will be used in the method body, they do not have to be previously defined The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter
698
Adrian Ilie - COMP 14 - Summer 2005
Return Value Value-returning methods The method returns the result of some operations Like mathematical functions Return one single value Void methods Perform operations but return no value
699
Value-Returning Methods
Adrian Ilie - COMP 14 - Summer 2005 Value-Returning Methods Think mathematical function f(x) = 2x + 5 f(x, y) = 2x + y f(1) = 7 f(1, 5) = 7 f(2) = 9 f(2, 3) = 7 f(3) = 11 f(3, 1) = 7 Can have multiple arguments (parameters) Only one result of the function
700
Value-Returning Methods Uses
Adrian Ilie - COMP 14 - Summer 2005 Value-Returning Methods Uses Save the value for future calculation Use the value in a calculation Print the value x = Math.pow (y, 2); z = a + Math.pow (y, 2) + x; System.out.println (Math.pow (y, 2));
701
Adrian Ilie - COMP 14 - Summer 2005
Return Type Indicates the type of value that the method evaluates to: primitive data type class name void reserved word indicating that nothing is returned When a value is returned, the method call is replaced with the returned value In this example, 'e' and "Heels" are called actual parameters -- because they are the actual values that we want the method to use. int number = countCharInWord ('e', "Heels"); 2
702
Adrian Ilie - COMP 14 - Summer 2005
The return Statement Tells the computer to "return" back to where the call was originally made. Specifies the value that will be returned return expression; The data type of expression must match the method's return type Methods with return types of void usually don't (but can) have a return statement Value-returning methods must have at least one return statement
703
Adrian Ilie - COMP 14 - Summer 2005
Void Methods Do not return a value Have a return type of void Similar in structure to value-returning methods Call to method is always a stand-alone statement Can use return statement to exit method early
704
Adrian Ilie - COMP 14 - Summer 2005
The main Method The main method looks just like all other methods public static void main (String[] args) modifiers return type method name parameter list
705
Adrian Ilie - COMP 14 - Summer 2005
Method Body The method header is followed by the method body public static int countCharInWord (char ch, String word) { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count; ch and word are local data They are created each time the method is called, and are destroyed when it finishes executing The return expression must be consistent with the return type
706
Adrian Ilie - COMP 14 - Summer 2005
Parameters Each time a method is called, the actual parameters in the call are copied into the formal parameters int num = countCharInWord ('e', "Heels"); public static int countCharInWord (char ch, String word) { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count;
707
Adrian Ilie - COMP 14 - Summer 2005
Parameters Formal parameters variable declarations in the method header automatic local variables for the method Actual parameters actual values that are passed to the method can be variables, literals, or expressions printStars (35); printStars (30 + 5); int num = 35; printStars (num);
708
Parameters Primitive Data Type Variables
Adrian Ilie - COMP 14 - Summer 2005 Parameters Primitive Data Type Variables If a formal parameter is a variable of a primitive data type, can it be modified inside a method? The value from the actual parameter is copied There is no connection between variables inside the method and outside Conclusion: it cannot be modified!!
709
Parameters Reference Variables
Adrian Ilie - COMP 14 - Summer 2005 Parameters Reference Variables If a formal parameter is a reference variable, can the object be modified inside a method? The address from the actual parameter is copied The local reference variable points to the same object Conclusion: it can be modified!!
710
Adrian Ilie - COMP 14 - Summer 2005
Primitive Data Types What if we want to modify a variable of a primitive data type inside a method? Encapsulate it in a class Example: IntClass (ch. 6, p. 306/350) IntClass is a class suggested in the book, but it is not a built-in class in Java!!!
711
Adrian Ilie - COMP 14 - Summer 2005
Overloading Methods Overloading - the process of using the same method name for multiple methods The signature of each overloaded method must be unique number of parameters type of the parameters not the return type of the method, though The compiler determines which version of the method is being invoked by analyzing the parameters
712
Adrian Ilie - COMP 14 - Summer 2005
Constructors public class Rectangle { private int length; private int width; Rectangle r2 = new Rectangle (5, 10); public Rectangle () { length = 0; width = 0; } Constructors can be overloaded, too. public Rectangle (int l, int w) { length = l; width = w; }
713
Adrian Ilie - COMP 14 - Summer 2005
The toString Method Special method in Java classes Produces a String object based on the current object, suitable for printing Mapped to the '+' operator Also called when the object is a parameter in a print() or println() method There is a default toString method, but it's better if we write our own System.out.println(r1); System.out.println(r1.toString());
714
Adrian Ilie - COMP 14 - Summer 2005
The Reference this Reserved word Refers to instance variables and methods of a class Allows you to distinguish between member variables and local variables with the same name
715
Adrian Ilie - COMP 14 - Summer 2005
Rectangle.java public class Rectangle { private int length; private int width; public Rectangle (int length, int width) this.length = length; this.width = width; }
716
Review Classes and Methods ReverseString.java
When do you use dot operator (.) to access methods? Must use dot operator to access method that is in a different class To access a method in ReverseString from ReverseTester, use dot operator To access a method in ReverseString from ReverseString, NO dot operator
717
Review Classes and Methods ReverseString.java
When do you use public vs. private? Use private: When the method or data member is only going to be accessed inside the same class Use public: When the method or data member is going to be accessed outside the class Anything that is called, or used, inside ReverseTester class must be public
718
Review Classes and Methods ReverseString.java
Why did we not use static in ReverseString class? When and why do we use static? Do not need object to use method/variable Consistent among all objects Shared among all objects of the class
719
Review Classes and Methods ReverseString.java
Why did we not use static in ReverseString class? When and why do we use static? Want all objects of class to share one copy of data Do not need method/variable to be object specific NOTE: Can't call a non-static method from a static method Can't access non-static variables from a static method
720
Review Classes and Methods ReverseString.java
Why was there no main method in ReverseString class? Only a driver class (a class that tests your program) has a main method General rule: For each program you write, there will only be one main method Here, it was given in ReverseTester class
721
Communication between Classes
Methods provide communication between methods Parameters provide input into class Return value provides output public returnType methodName ( formal parameters ) Output from method Input to method
722
Adrian Ilie - COMP 14 - Summer 2005
Arrays An array is a list of values that can be represented by one variable Members of an array must all have the same data type Each value is stored at a specific, numbered position in the array the number corresponding to each position is called an index or subscript All arrays have a length number of elements the array can hold
723
Adrian Ilie - COMP 14 - Summer 2005
1 2 3 Review Arrays Declaration int[] counts; Instantiation counts = new int[50]; Initialization / Access for (int i=0; i<counts.length; i++) { counts[i] = 0; } Initializer List declaration, instantiation, and initialization double[] grades = {98.7, 72.4, 87.5}; int[] numbers = {num, num+1, num+2, num+3}; can use variables and expressions as initial values
724
Parallel Arrays Arrays are parallel if corresponding components hold related information String[] studentName; double[] studentGPA; For example, studentName and studentGPA are parallel if studentGPA[3] is the GPA of the student with studentName[3].
725
Adrian Ilie - COMP 14 - Summer 2005
Copying Arrays counter int[] counter = {1, 2, 3, 4, 5}; int[] temp = new int[counter.length]; temp 1 2 3 4 1 1 2 3 4 1 2 2 3 3 4 4 5 5 i for (int i=0; i<counter.length; i++) { temp[i] = counter[i]; } 3 5 2 4 1
726
Adrian Ilie - COMP 14 - Summer 2005
Arrays as Parameters Entire array can be passed as a parameter method can change elements of the array permanently since we're passing a reference Elements of an array can be passed as parameters, too normal rules apply…
727
Adrian Ilie - COMP 14 - Summer 2005
Arrays as Parameters Entire array can be passed as a parameter method can change elements of the array permanently since we're passing a reference Elements of an array can be passed as parameters, too normal rules apply…
728
Adrian Ilie - COMP 14 - Summer 2005
Arrays of Objects Can use arrays to manipulate objects Create array of objects Must instantiate each object in array classname[] array = new classname[size]; for(int j=0; j <array.length; j++) { array[j] = new classname(); }
729
Adrian Ilie - COMP 14 - Summer 2005
Binary Search Requires ordered (sorted) list Set searchRange to the entire list Repeat: pick a “test value” in the middle of searchRange if test value == value searching for Stop! if test value > value searching for searchRange = lower half of searchRange if test value < value searching for searchRange = upper half of searchRange Binary search is a little more intelligent searching
730
Adrian Ilie - COMP 14 - Summer 2005
Example Trial 1 Looking for 46 2 SearchRange in yellow 3
731
Selection Sort Methods
Adrian Ilie - COMP 14 - Summer 2005 Selection Sort Methods Scan the list to find the smallest value Swap that value with the value in the first position in the list Scan rest of list to find the next smallest value Swap that value with the value in the second position in the list And so on, until you get to the end of the list loop
732
Adrian Ilie - COMP 14 - Summer 2005
Inheritance JFrame is a class provided by the package javax.swing Instead of instantiating an object of the JFrame class, we're going to extend the JFrame class (called inheritance). The new class "inherits" features (including methods and variables) from the existing class -- big time-saver! We can use all of the methods and variables from JFrame, while adding our own. If you take COMP 114, you'll learn a lot more about inheritance
733
Adrian Ilie - COMP 14 - Summer 2005
Extending JFrame Use the modifier extends, which is a reserved word JFrame is the superclass BigGUI is the subclass It is ok to learn the recipe public class BigGUI extends JFrame { }
734
Adrian Ilie - COMP 14 - Summer 2005
Next Step We'll need a constructor for BigGUI set the window title setTitle set the window size setSize set the default operation when the close button is pressed setDefaultCloseOperation display the window setVisible(true) We'll need a main method create an object of the BigGUI class (which will call the constructor)
735
Adrian Ilie - COMP 14 - Summer 2005
import javax.swing.*; // needed for JFrame public class BigGUI extends JFrame { private final static String TITLE = “Big GUI"; private final static int WIDTH = 700; private final static int HEIGHT = 600; public BigGUI() // constructor { setTitle(TITLE); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { BigGUI gui = new BigGUI(); } } Adrian Ilie - COMP 14 - Summer 2005 BlackjackUITest1
736
Adrian Ilie - COMP 14 - Summer 2005
Adding Things Access the content pane so we can add things (buttons, labels, images) Container class is provided by the java.awt package add import statement for java.awt Then, we set the layout type and add things to the content pane Container content = getContentPane();
737
Adrian Ilie - COMP 14 - Summer 2005
Layout Managers FlowLayout default components are added left to right, top to bottom BorderLayout consists of NORTH, SOUTH, EAST, WEST, CENTER regions size of CENTER region depends on the number of components in the EAST and WEST regions GridLayout define number of rows and columns to get equally sized cells cells are filled left to right, top to bottom
738
Adrian Ilie - COMP 14 - Summer 2005
BorderLayout Select layout for BigGUI as BorderLayout When adding components with BorderLayout, you have to specify the section (using NORTH, SOUTH, EAST, WEST, CENTER constants from BorderLayout class) content.setLayout(new BorderLayout()); content.add(item, BorderLayout.SECTION);
739
Adrian Ilie - COMP 14 - Summer 2005
JLabels We'll identify the regions of the BorderLayout with labels (text areas) JLabel is a region of text can be assigned an alignment (left-justified, right-justified, centered) Text can be changed with setText method JLabel northLabel = new JLabel ("NORTH", SwingConstants.CENTER); JLabel southLabel = new JLabel ("SOUTH"); northLabel.setText ("Changed Text");
740
Adrian Ilie - COMP 14 - Summer 2005
Colors Set the background color of the content pane Set the foreground color of the text (JLabels) Use Color class from the java.awt package Available colors pg. 734 constants (but lowercase) Methods darker() - darkens the color brighter() - brightens the color content.setBackground(Color.blue.darker().darker()); northLabel.setForeground(Color.white);
741
Adrian Ilie - COMP 14 - Summer 2005
Adding Images We can create images and associate them with labels ImageIcon use JPG or GIF images Use setIcon method from JLabel class ImageIcon image = new ImageIcon ("img/0.gif"); filename centerLabel.setIcon (image);
742
Text Position Relative to Icon
Adrian Ilie - COMP 14 - Summer 2005 Text Position Relative to Icon label.setVerticalTextPosition(vposition); label.setHorizontalTextPosition(hposition); SwingConstants.TOP SwingConstants.CENTER SwingConstants.BOTTOM SwingConstants.LEFT SwingConstants.CENTER SwingConstants.RIGHT
743
Adrian Ilie - COMP 14 - Summer 2005
BigGUI.java Add icon.
744
Adrian Ilie - COMP 14 - Summer 2005
JLabel and JTextField Very similar. With JTextField we can also type data from outside and access it in the program. JLabel output=new JLabel(); JTextField input=new JTextField(); … String inputStr=input.getText(); output.setText(“OUTPUT RESULT”);
745
Adrian Ilie - COMP 14 - Summer 2005
Using Buttons Create JButton objects Buttons generate events when clicked Add event handlers Inside event handler, code operations to be executed when button is clicked
746
Adrian Ilie - COMP 14 - Summer 2005
Adding Buttons To create a button, we use the JButton class Add button to the content pane Change text of the button with the setText method Enable/disable the button with setEnabled method JButton toLower = new JButton (“To Lower Case"); content.add(toLower); toLower.setText(“Convert to Lower Case"); toLower.setEnabled(false);
747
Adrian Ilie - COMP 14 - Summer 2005
Buttons and Events Pressing buttons triggers action events Setup a listener for the event actionPerformed method from ActionListener class ActionListener class from the java.awt.event package something else to import
748
Adrian Ilie - COMP 14 - Summer 2005
ActionListener Special type of class, called interface Interface - class that contains only the method headings (no method bodies) public interface ActionListener { public void actionPerformed (ActionEvent e); }
749
Adrian Ilie - COMP 14 - Summer 2005
ActionListener In order to handle an event, define a class that will implement ActionListener. Make the class ButtonHandler an internal class of our main class. In ButtonHandler, code the method actionPerformed private class ButtonHandler implements ActionListener
750
Adrian Ilie - COMP 14 - Summer 2005
ActionListener Declare a ButtonHandler that will be a data member of the main class. Instantiate the ButtonHandler (e.g. in the constructor) Once the JButton object is created, register the action listener: private ButtonHandler toLowerHandler; toLowerHandler=new ButtonHandler(); toLower.addActionListener(toLowerHandler);
751
Adrian Ilie - COMP 14 - Summer 2005
actionPerformed Variables we want to access inside the actionPerformed methods, must be declared as member variables of the main class not local to constructor Make input, output, and the buttons member variables
752
Adrian Ilie - COMP 14 - Summer 2005
Applets A Java application is a stand-alone program with a main method A Java applet is a Java program that is intended to be transported over the web and executed using a web browser an applet doesn't have a main method needs an extra import statement: import java.applet.Applet;
753
Adrian Ilie - COMP 14 - Summer 2005
Applet Methods Several methods from Applet class that are invoked automatically at certain points in an applet's life init - executed only once when the applet is initially loaded start - called when applet becomes active (when browser loads / returns to the page) stop - called when applet becomes inactive (when browser leaves the page) paint - automatically executed and is used to draw the applets contents
754
Converting Apps to Applet
Adrian Ilie - COMP 14 - Summer 2005 Converting Apps to Applet See Ch 13, pgs ( ) Extends JApplet instead of JFrame No main method No constructor put code from constructor in init() method No setVisible, setTitle, or setSize methods
755
Adrian Ilie - COMP 14 - Summer 2005
Applets and the Web An applet is embedded into an HTML file using a tag that references the bytecode file (ClassName.class) of the applet class It is actually the bytecode version of the program that is transported across the web The applet is executed by a Java interpreter that is part of the browser this Java interpreter not included in Windows XP, must download from java.com
756
Adrian Ilie - COMP 14 - Summer 2005
Applets and the Web Basic HTML file for an applet: Can also specify size of applet window Put the applet HTML file (named something.html) and your Java applet bytecode (named ClassName.class) in your public_html folder in AFS space. <html> <body> <applet code = "ClassName.class"> </applet> </body> </html> <applet code="ClassName.class" height=200 width=300> </applet> The whole idea behind applets was to be able to run a program over the web
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.