comp 14 introduction to programming miguel a. otaduy may 14, 2004

47
COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Post on 21-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

COMP 14Introduction to Programming

Miguel A. Otaduy

May 14, 2004

Page 2: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Today

• Variables and expressions

• Input/Output

• Writing a whole program

Page 3: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Variables

• Associated with data– Input data– Output data– Intermediate data

• We need to define:– Data type– Identifier

• Values will be assigned in expressions

Page 4: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Variables. Steps

1. Identify all data from the algorithm2. Determine data types (based on the

range and nature of the values)3. Find meaningful names

• Example: Ch. 1, Exercise 11. Compute average miles per gallon.

Page 5: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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 classint numStudents;

• Multiple variables (of the same data type) can be declared on a single lineint numStudents, numGrades, total;

Page 6: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 7: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Assignment

• The assignment operator has a lower precedence than the arithmetic operators

First the expression on the right handside of the = operator is evaluated

Then the result is stored in thevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

Page 8: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Assignment• The right and left hand sides of an assignment

statement can contain the same variable

First, one is added to theoriginal value of count

Then the result is stored back into count(overwriting the original value)

count = count + 1;

Page 9: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Example (miles per gallon)• Write assignments and expressions

• Declaration of variables (good style)a) At the beginningb) Before being used

Page 10: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Named Constantstatic 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 centimetersfinal double CM_PER_INCH = 2.54;

Page 11: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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 = 5 + 4 - 2;num = num * 2;num = 3.4 + 5;

unknown

3

7

14

error

would give an error since 3.4 + 5 wouldnot result in an int

Page 12: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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.

1. i = i + 5;

2. x + 2 = x;

3. x = 2.5 * x;

4. percent = 10%

validinvalid

valid

invalid

Page 13: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Input

1. Standard input

2. Dialog windows (on Monday)

3. File (on Monday)

Page 14: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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)

Page 15: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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?

Page 16: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Reading Keyboard InputThe 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 lineat once

Page 17: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Reading Keyboard Input

• The readLine method of the BufferedReader class reads an entire line of input as a String

String line = keyboard.readLine();

Page 18: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Example (miles per gallon)

• Input odometer values

• Input gallons put in the car

Page 19: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

String to Numbers

• String to intInteger.parseInt(strExpression)

Integer.parseInt("6723") 6723

• String to floatFloat.parseFloat(strExpression)

Float.parseFloat("345.76") 345.76

• String to doubleDouble.parseDouble(strExpression)

Double.parseDouble("1234.56") 1234.56

Page 20: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Example (miles per gallon)

• Convert miles to int

• Convert gallons to double

Page 21: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Output

• Standard output device is usually the monitor

• Access the monitor using the standard output object– System.out

• Two methods to output a string:1.print

2.println Puts the cursor at the next line

Page 22: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Examples

System.out.println ("Hi");System.out.println ("There");HiThere

int num = 5;System.out.println ("The sum is " +

(num + 3));The sum is 8

int num = 5+3;System.out.println (num);8

System.out.print ("Hi");System.out.println ("There");HiThere

Page 23: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

String Concatenation

• A string cannot be split between two linesString 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?”;

How are you doing today?greeting

X

Page 24: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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 = 1226str

Page 25: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Example (miles per gallon)

• Output result

• Formatting numeric strings

Page 26: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 27: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 28: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Package

java.langjava.appletjava.awtjavax.swingjava.netjava.utiljavax.xml.parsers

Purpose

General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilities and componentsNetwork communicationUtilitiesXML document processing

Packages

• The classes of the Java standard class library are organized into packages.

• Some of the packages in the standard class library are:

Page 29: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 30: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 31: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Using Predefined Classes and Methods• Example method call:int num = (int) Math.round (4.6);

– why don't we have to import the Math class?

• (Dot) . Operator: used to access the method in the class

Page 32: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 33: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 34: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 35: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 36: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 37: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 38: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 39: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 40: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

Skeletonimport statements if any

public class ClassName{

declare named constants and/or stream objects

public static void main (String[] args) throws IOException

{variable declarationsexecutable statements

}}

Page 41: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 42: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 43: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 44: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 45: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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

Page 46: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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 */

Page 47: COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004

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 Sunday night.– Hint***

• Read Ch. 3