cop3502 programming fundamentals for cis majors 1 2.pdf · suppose we want to write a simple...

74
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi

Upload: dangnhu

Post on 03-Apr-2018

216 views

Category:

Documents


2 download

TRANSCRIPT

COP3502

Programming

Fundamentals

for CIS Majors 1

Instructor: Parisa Rashidi

Two other TA -Hengxing Tan, [email protected], E402, Monday, 1:00 pm – 3:00 pm -Haitham Gabr, [email protected], E309, Thursday, 10:00 am – 12:00 pm

PA 1 extended to Monday Jan 23

No need to turn in actual program for HW

SAKAI

Objectives

OOP

class definition

packages

GUI Dialog

Last Class

Program design

Java primitive data types

Java operators

Input from the console & GUI

Programming style, and naming conventions

Objectives

Algorithm Design

Suppose we want to write a simple program

for computing the area of a circle.

Where do we start?

Algorithms

Writing a program is

1. Designing algorithms

2. Translating algorithms into code

Algorithms can be in

Natural language

Pseudo-code

Natural language mixed with programming

code

Algorithms

1. Read in the radius

2. Compute the area using the following

formula

3. Display the area

Algorithms

Area = radius × radius × 𝜋

Every Java program begins with a class

Algorithms to Code

public class ComputeArea {

}

Every Java program should have a main

method

Algorithms to Code

public class ComputeArea {

public static void main(String[] args)

{

… }

}

Identify steps

Algorithms to Code

public class ComputeArea {

public static void main(String[] args)

{

//step 1: read in radius

//step 2: compute area

//step 3: Display the area

}

}

Identify variables

Algorithms to Code

public class ComputeArea {

public static void main(String[] args)

{

double radius;

double area;

//step 1: read in radius

//step 2: compute area

//step 3: Display the area

}

}

Fill in the steps

Algorithms to Code

public class ComputeArea {

public static void main(String[] args)

{

double radius;

double area;

//step 1: read in radius radius = 20;

//step 2: compute area

//step 3: Display the area

}

}

Fill in the steps

Algorithms to Code

public class ComputeArea {

public static void main(String[] args)

{

double radius;

double area;

//step 1: read in radius radius = 20;

//step 2: compute area

area = radius * radius * 3.14;

//step 3: Display the area

}

}

Fill in the steps

Algorithms to Code

public class ComputeArea {

public static void main(String[] args)

{

double radius;

double area;

//step 1: read in radius radius = 20;

//step 2: compute area

area = radius * radius * 3.14;

//step 3: Display the area

System.out.println(“area is: ” + area);

}

}

Variables

A variable stores a piece of data

int x =10;

Identifier

Name of your variable

1. letters, digits, underscores (_), dollar signs ($)

2. Cannot start with a digit

3. Cannot be a reserved word

E.g. cannot be: class

Variable

X

23

Variable

Identifier

Literal

Example

Do not forget that Java is case sensitive!

Declaring Variables

int x = 0; // Declare x to be an

// integer variable;

// e.g. 101

double radius = 10.0; // Declare radius to

// be a double variable;

// e.g. 101.89

char y = ‘a’; // Declare y to be a

// character variable;

// e.g. ‘d’

Example

Variable

double radius;

// Compute the first area

radius = 1.0;

double area = radius * radius * 3.14159;

// Compute the second area

radius = 2.0;

area = radius * radius * 3.14159;

Value is constant, doesn’t change

Use “final” keyword to declare a value as

constant

Constants

final datatype CONSTANTNAME = VALUE;

Example:

final double PI = 3.14159;

final int SIZE = 3;

Numbers in More Detail ..

Different types of numeric data

Numeric Data Types

Name Range Storage Size

byte –2

7 (-128) to 2

7–1 (127) 8-bit signed

short –2

15 (-32768) to 2

15–1 (32767) 16-bit signed

int –2

31 (-2147483648) to 2

31–1 (2147483647) 32-bit signed

long –2

63 to 2

63–1 64-bit signed

(i.e., -9223372036854775808

to 9223372036854775807)

float Negative range: 32-bit IEEE 754

-3.4028235E+38 to -1.4E-45

Positive range:

1.4E-45 to 3.4028235E+38

double Negative range: 64-bit IEEE 754

-1.7976931348623157E+308 to

-4.9E-324

Positive range:

4.9E-324 to 1.7976931348623157E+308

Numeric Data Types

byte= 8 bits

short

int

long

Sign bit

float

double

Integer calculations are precise.

Calculations involving floating-point

numbers are approximated

E.g. below displays 0.5000000000000001, not 0.5

E.g. below displays 0.09999999999999998, not

0.1

Floating Point Numbers

System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);

System.out.println(1.0 – 0.9);

A constant value appearing directly in the

program

E.g.

You can use append letters to indicate type

Literal

int i = 34;

long x = 10000;

double d = 5.0;

1000000L; //long

5.0f; //float

A literal should fit in its variable

The following example is wrong.

myVar can not hold this number.

Byte range = [-128, 127] > 1000

Literal

byte myVar = 10000;

Floating point literals can be specified in

scientific notation, e.g.

1.23456e2

123.456 = 1.23456 * (10^2)

Pitfall:

Here “e” or “E” is NOT the natural logarithm’s

base (2.718). It is 10.

Scientific Notation

Different types of numeric operators

Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

Be careful!

5 / 2 yields an integer 2

5.0 / 2 yields a double value 2.5

Remainder can be very useful

Even numbers % 2 = 0

Today is Saturday and you and your friends are

going to meet in 10 days. What day is in 10 days?

Numeric Operators

Saturday is the 6th day in a week

A week has 7 days

After 10 days

The 2nd day in a week is Tuesday (6 + 10) % 7 is 2

Missed your lab session?

Friday at 5:30 pm room E116

Friday at 5:30 pm room E113

Course Website + Sakai

Homework 1 due today

Use Sakai to submit HW/PA

HW

In-line, .doc, .pdf

PA

.java

Agenda

Primitive data types

Integer: byte, short, int, long

Floating point: float, double

Primitive operations

+-/*%

precedence

Last Class

Operators have precedence

1. Parentheses ()

2. *, /, %

3. +,-

4. …

Arithmetic Expressions

3 + 4 * 4 + 5 * (4 + 3) - 1

3 + 4 * 4 + 5 * 7 – 1

3 + 16 + 5 * 7 – 1

3 + 16 + 35 – 1

19 + 35 – 1

54 - 1

53

(1) inside parentheses first

(2) multiplication

(3) multiplication

(4) addition

(6) subtraction

(5) addition

Shortcut operators for assignment

Shortcut Operators

Operator Example Equivalent

+= i += 8 i = i + 8

-= f -= 8.0 f = f - 8.0

*= i *= 8 i = i * 8

/= i /= 8 i = i / 8

%= i %= 8 i = i % 8

Increment, decrement operators

++/--

Operator Name Description

++var pre-increment The expression (++var) increments var by 1 and evaluates

to the new value in var after the increment.

var++ post-increment The expression (var++) evaluates to the original value

in var and increments var by 1.

--var pre-decrement The expression (--var) decrements var by 1 and evaluates

to the new value in var after the

decrement.

var-- post-decrement The expression (var--) evaluates to the original value

in var and decrements var by 1.

Increment, decrement operators

++/--

int i = 10;

int newNum = 10 * i++;

int newNum = 10 * i;

i = i + 1;

Same effect as

int i = 10;

int newNum = 10 * (++i);

i = i + 1;

int newNum = 10 * i;

Same effect as

Example

When having different types of operands

Operands will be automatically converted to

the largest operand in the expression

Conversions

byte i = 100;

long k = i * 3 + 4;

double d = i * 3.1 + k / 2;

Implicit casting (type widening)

A small number fits easily in a large variable

Explicit casting (type narrowing)

3.9 cannot be fit in an int, so fraction part is

truncated.

Overflow: value too large to be stored

Conversions

int x = 3; double d = x;

double d = 3.9;

int i = (int)d;

byte b = 300;

Tracing a Simple Program

Trace of Program

public class ComputeArea {

/** Main method */

public static void main(String[] args) {

double radius;

double area;

// Assign a radius

radius = 20;

// Compute area

area = radius * radius * 3.14159;

// Display results

System.out.println("The area for the circle of radius " +

radius + " is " + area);

}

}

no value radius

allocate memory for radius.

(it is a “variable”)

Trace of Program

public class ComputeArea {

/** Main method */

public static void main(String[] args) {

double radius;

double area;

// Assign a radius

radius = 20;

// Compute area

area = radius * radius * 3.14159;

// Display results

System.out.println("The area for the circle of radius " +

radius + " is " + area);

}

}

no value radius

no value area

Allocate memory for area.

(It is a “variable”).

Trace of Program

public class ComputeArea {

/** Main method */

public static void main(String[] args) {

double radius;

double area;

// Assign a radius

radius = 20;

// Compute area

area = radius * radius * 3.14159;

// Display results

System.out.println("The area for the circle of radius " +

radius + " is " + area);

}

}

20 radius

no value area

Assign value to radius

Trace of Program

public class ComputeArea {

/** Main method */

public static void main(String[] args) {

double radius;

double area;

// Assign a radius

radius = 20;

// Compute area

area = radius * radius * 3.14159;

// Display results

System.out.println("The area for the circle of radius " +

radius + " is " + area);

}

}

20 radius

1256.636 area

Compute area and assign it to

the variable

Other Data Types in Detail ..

char ch = ‘a’;

ASCII

Initial encoding

Unicode

More recent encoding, allowing international

encoding

A 16-bit encoding scheme, preceded by \u,

expressed in four hexadecimal numbers that

run from '\u0000' to '\uFFFF'.

char ch = ‘\u0003’;

Character Type

How to declare?

char letter = 'A'; (ASCII)

char numChar = '4'; (ASCII)

char letter = '\u0041'; (Unicode)

char numChar = '\u0034'; (Unicode)

Representing a numerical code (e.g. ‘a’=97)

You can use +/- on char

Character Type

char ch = 'a';

System.out.println(++ch);

Java characters use Unicode

Supports display of written texts in the world’s

diverse languages.

Character Type

Unicode \u03b1 \u03b2 \u03b3

for three Greek letters

Special characters called “escape” characters

Escape Characters

Description Escape Sequence Unicode

Backspace \b

\u0008

Tab \t

\u0009

Linefeed \n

\u000A

Carriage return \r

\u000D

Backslash \\

\u005C

Single Quote \'

\u0027

Double Quote \"

\u0022

Example 1

System.out.println(“Java is fun!”);

Output: Java is fun!

Example 2

System.out.println(“Java is \n fun!”);

Output: Java is

fun!

Equivalent to:

System.out.println(“Java is”);

System.out.println(“fun!”);

Escape Characters

Char type is one character

E.g. ‘a’

String type is sequence of characters

String x = “Java is fun”;

Not a primitive type!

A predefined class in Java

Reference type (more later in Chapter 7)

String Type

Concatenate strings

1. String message = "Welcome " + "to " + "Java";

//message becomes “Welcome to Java”

2. String s1 = "Chapter" + 2;

// s1 becomes Chapter2

3. String s2 = "Supplement" + 'B';

// s2 becomes SupplementB

String Type

Equivalent class for each data type

Byte, Short, Integer, Long, Float, Double, Character

Use the following method to convert from String

Use the following method to convert from String

Converting Strings

int x = Integer.parseInt(“85”);

double y=Double.parseDouble(“85.7”);

Input

Class is a template for creating instances

How to create instances of a class?

Class

ClassName instanceName = new ClassName(IntialInputParam);

Dog d1= new Dog(2,”Max”);

Dog d2= new Dog(3,”Gizmo”);

In java, usually we create instances of class to call methods

d1.eat();

d2.bark();

Some classes, provide methods which can be used without creating instances of the class

static

public static void main()

System.out.println();

JOptionPane.showMessageDialog()

Method Call

1. Create a Scanner object

Scanner input = new Scanner(System.in);

2. Use one of the methods below

Input

Method You will get

next() String

nextByte() byte

nextShort() short

nextInt() int

nextLong() long

nextFloat() float

nextDouble() double

nextBoolean() boolean

Write a program that obtains hours and

minutes from seconds

Program

Run DisplayTime

HW2 is available on Sakai

No class next Monday

TAs responsible for grading your HW, PA

Haitham responsible for PA (all sections)

HW as following

Agenda

HW Section TA

4185, 6769 Ted

5313, 6761 Hengxing

6736, 7091 Shuang

6766, 6764 Yu-Song

6753, 9285 Aysegul

1F70, 1H38 Haitham

Shortcut operators

char, String

Wrapper class for primitive data types

Byte, Short, Integer, Long, Float, Double,

Character

Creating instance from a class

Using methods

static

Non-static

Input

Last Class

Write a program that displays the sales tax.

Program

SalesTax Run

GUI= Graphical User Interface

GUI Input

String input = JOptionPane.showInputDialog( "Enter an input");

GUI= Graphical User Interface

GUI Input

String string = JOptionPane.showInputDialog(

null, “Enter a year:”, “Example 2.2 Input (int)”,

JOptionPane.QUESTION_MESSAGE);

Programming Style

Appropriate Comments

Naming Conventions

Proper Indentation and Spacing Lines

Block Styles

Programming Style

Comment is important

Documenting your program

Appropriate Comments Include a summary at the beginning of the program

what the program does

its key features

its supporting data structures

For this class:

your name, class section, date, and a brief description at the beginning of the program.

Programming Style

Choose meaningful and descriptive names, not cryptic names!

Variables and method names

Use lowercase.

If the name consists of several words, capitalize the first letter of each subsequent word in the name.

computeArea()

Class names Capitalize the first letter of each word in the name

BankAccount

Constants Capitalize all letters in constants, use underscores

MAX_VALUE

Programming Style

Indentation

Blocking styles

Spacing

Use blank line to separate segments of the code.

Programming Style

public class Test

{

public static void main(String[] args)

{

System.out.println("Block Styles");

}

}

public class Test {

public static void main(String[] args) {

System.out.println("Block Styles");

}

}

End-of-line

block style

Next-line

block style

Indentation

Programming Errors

Syntax Errors

Detected by the compiler

E.g. “iNT x;” instead of “int x;”

Runtime Errors

Causes the program to abort

E.g. x= 3/0;

Logic Errors

Produces incorrect result

Tax = 1.0 * income;

Programming Errors

Syntax Errors

Syntax Errors

public class ShowSyntaxErrors {

public static void main(String[] args) {

i = 30;

System.out.println(i + 4);

}

}

Runtime Errors

Runtime Errors

public class ShowRuntimeErrors {

public static void main(String[] args) {

int i = 1 / 0;

}

}

Logical Errors

Error in design of program

E.g. using the wrong formula for computing the area of

a circle

Logical Errors

Logical Errors are called “bugs”

The process of finding and correcting errors is called debugging.

narrow down to where the bug is located

1. hand-trace the program (read your program)

Difficult

2. insert print statements to show the values of

the variables

Still not very effective

3. Use a debugger utility

Debugging

History of term “bug”

Debugging

Admiral Grace

Hopper

Debugger: the program for debugging

Usually part of IDE

It allows you to Execute a single statement at a time

Trace into or stepping over a method

Set breakpoints

Display variables

Debugging