• No results found

AP COMPUTER SCIENCE

N/A
N/A
Protected

Academic year: 2020

Share "AP COMPUTER SCIENCE"

Copied!
46
0
0

Loading.... (view fulltext now)

Full text

(1)

AP COMPUTER

SCIENCE

(2)

CHAPTER 2

(3)

STATEMENTS VS. EXPRESSIONS

⦿ A statement is a complete snippet of code that can be executed

◼ Statements are terminated by semi-colons

◼ A statement typically does not represent a value

⦿ An expression is something that has a value, including:

◼ Literals

◼ Variables

◼ Results of operators

(4)

TYPES

⦿

Every expression and value in Java has a

type.

⦿

Types differentiate how data is interpreted.

◼ Why is this necessary?

⦿

Types also dictate what operations can be

performed.

(5)

ARITHMETIC

⦿

Integers are represented in Java by the

int

type

⦿

int

is one of several primitive types in Java

◼ Primitive types are built into Java

◼ Primitives cannot have messages passed to them!

(6)

ARITHMETIC

⦿

All four basic arithmetic operations exist in

Java as operators:

◼ Addition: +

◼ Subtraction:

-◼ Multiplication: *

◼ Division: /

⦿

There is also the modulo (remainder)

operator:

(7)

ARITHMETIC

⦿

Addition, subtraction, and multiplication

work just like normal arithmetic:

System.out.println(4 + 7); // ???

System.out.println(12 – 9); // ???

System.out.println(5 * 3); // ???

⦿

These operations can be strung together:

(8)

ARITHMETIC

⦿ Division with integers gives the quotient only: System.out.println(4 / 2); // ???

System.out.println(10 / 3); // ???

System.out.println(1 / 2); // ???

⦿ The modulo operators gives the remainder: System.out.println(4 % 2); // ???

System.out.println(10 % 3); // ???

(9)

ARITHMETIC

⦿

The normal arithmetic order of operations is

followed (including parentheses):

◼ Modulo with multiplication/division

System.out.println(3 + 4 * 5); // ???

System.out.println((5 – 1) / 2); // ???

(10)

NON-INTEGERS

⦿

Real numbers are represented in Java using

the

double

type

⦿

Arithmetic on

double

s

is the same as on

int

s, with two exceptions:

◼ Division is real number division

(11)

ARITHMETIC

⦿ Exercise 1: Write a program to convert a temperature from Fahrenheit to Celsius.

⦿ Exercise 2: Write a program to print out the digits of a five digit integer, one per line.

⦿ Exercise 3: Write a program to reverse the digits of a three digit integer

e.g. 123 -> 321

(12)

VARIABLES

⦿ To store data for later use, we use variables:

String myString;

myString = “Hello, world!”; System.out.println(myString);

⦿ Before using a variable, we must declare it using the following syntax:

<type> <name>;

e.g. String word;

(13)

ASSIGNMENT

⦿ Once a variable has been declared, we must assign it a value

String myString; Declaration

myString = “Hello, world!”; Assignment

⦿ Until a variable has been assigned a value, it is useless

⦿ You can combine a declaration and an assignment into one statement, called an initialization

(14)

ASSIGNMENT

⦿

Variables and assignments are independent:

String str1 = “Hello”; String str2 = str1;

str1 = “Goodbye”;

System.out.println(str2); // ???

⦿

Literals are not variables

String str;

(15)

ASSIGNMENT

⦿

Variables only hold one value at a time:

String str1 = “Hello”; String str2 = “Goodbye”; str1 = str2;

str2 = str1;

System.out.println(str1); // ???

(16)

VARIABLES

⦿ Exercise 1: Write a program to convert a temperature from Fahrenheit to Celsius.

⦿ Exercise 2: Write a program to print out the digits of a five digit integer, one per line.

⦿ Exercise 3: Write a program to reverse the digits of a three digit integer

e.g. 123 -> 321

(17)

CONSOLE INPUT

⦿

Input, despite being necessary for most

useful programs, is pretty complicated

⦿

Java has numerous methods for getting

input from a bunch of different sources

◼ keyboard, local files, web pages, network resources, etc.

⦿

For now, we will focus on one simple

(18)

CONSOLE INPUT

⦿ The simplest way to read input from the keyboard is to use a Scanner and the predefined stream System.in

Scanner keyboard = new Scanner(System.in);

⦿ Once you’ve done this, you can read a line of input using the nextLine method and store the result in a String

String input = keyboard.nextLine();

⦿ To read an int, use nextInt:

int x = keyboard.nextInt();

(19)

CONSOLE INPUT

⦿ Exercise 1: Write a program to ask the user their name and then greet them by name.

Hello, what’s your name? > Brett

Nice to meet you, Brett!

⦿ Exercise 2: Write a program to ask the user for two integers and then print out their product.

Enter first number > 5

Enter second number > 7

(20)

MINI-PROJECT

(21)

MORE ON PRIMITIVES

⦿

So far, we have seen two primitive types

(

int

and

double

)

(22)

MORE ON PRIMITIVES

Type Description Range of values

byte 8-bit signed integer -128 to 127

short 16-bit signed integer -32,768 to 32,767

int 32-bit signed integer -2, 147, 483, 648 to 2, 147, 483, 647

long 64-bit signed integer -9E18 to 9E18 (approx.)

float 32-bit floating point (real number)

double 64-bit floating point (real number)

char 16-bit Unicode character (unsigned)

(23)

MORE ON PRIMITIVES

⦿

int

,

short

, and

byte

values are all simple

integers:

◼ int i = 40000;

◼ short s = 1000;

◼ byte b = 100;

⦿

long

values require an ‘

L

’ to be appended:

(24)

MORE ON PRIMITIVES

⦿

float

s require appending an ‘

f

’:

◼ float f = 3.1415927f;

⦿

double

s have an optional appended ‘

d

’:

◼ double d1 = 2.718281828d;

(25)

MORE ON PRIMITIVES

⦿ chars are enclosed in single quotes:

◼ char c1 = ‘a’; ◼ char c2 = ‘5’;

Note that this is very

different from int i = 5;

◼ char c3 = ‘ ’;

⦿ Certain special chars require an escape

sequence (just like in

strings):

(26)

MORE ON PRIMITIVES

⦿ true and false are the only boolean values, and are reserved words:

◼ boolean b1 = true; ◼ boolean b2 = false;

⦿ The result of a Boolean expression is also a

boolean value:

◼ boolean b3 = x < 5;

(27)

TYPE CONVERSION

⦿ Some primitive types can be implicitly converted to one another:

int i = 10; long l = i;

⦿ Others require a explicit conversion, called a

cast:

double d = 5.0; int i2 = (int)d;

(28)

TYPE CONVERSION

⦿

Exercise: Try out the following expressions,

and see if you can determine any rules about

mixing types:

2.0 + 3 "1" + "2" 'a' + 1

3 / 2 + 1.0 "abc" + 1 + 2'A' + 1 1.0 + 3 / 2 1 + 2 + "abc"'e' – 'a'

(29)

TYPE CONVERSION

⦿ Exercise 2: Write a Java program to print the

“alpha-index” of the first five letters of a string (A=0, B=1, … , Z = 25)

⦿ Exercise 3: Write a Java program to perform a “Caesar shift” on a five-character string.

In a Caesar shift, each character is shifted forward three (A -> D, B -> E, C ->F, etc.)

(30)

COMPOUND ASSIGNMENT

⦿ Frequently in programming, we want to do something like this:

price = price * 1.09; // apply tax price = price + 2.95; // add shipping price = price – 5.00; // apply coupon

⦿ Because this is so common, Java gives us a shortcut for this kind of operation:

(31)

COMPOUND ASSIGNMENT

⦿ These operators are called compound assignment operators

⦿ There is a compound assignment operator corresponding to each arithmetic operator:

+ += - -= * *= / /= % %=

⦿ Since these are assignments, only variables can be on the left-hand side

◼ Any expression of the correct type can go on the right-hand

(32)

INCREMENT/DECREMENT

⦿ Even more common are these operations:

x = x + 1; x = x – 1;

⦿ How could we rewrite these using compound assignment?

x += 1; x -= 1;

⦿ Java lets us shortcut these operations even further with the increment and decrement operators:

(33)

INCREMENT/DECREMENT

⦿ These are called postfix operators, because the operator comes after the operand

There are also prefix versions of these (++x, --x)

◼ For now, assume the prefix and postfix versions are the same, and prefer the postfix version

⦿ As with compound assignment, only variables can be the operand

(34)

COMPOUND ASSIGNMENT

⦿ Exercise 1: Write a program to calculate and print the average of three integers. Use as few variables as possible and use compound

assignment.

(35)

MINI-PROJECT

⦿ Write a Java program to track an employee’s pay at their job. Your program should ask for the number of hours the employee worked each day Monday through Friday. You should then calculate and output the following information:

The total number of hours worked for the week

The employee’s gross pay (at a wage of $12.50 per hour)

(36)

FOR

LOOPS

⦿ Loops are a control flow structure that allows us

to repeat code

◼ Why might this be useful?

⦿ The simplest type of loop is the for loop

for (<initialization>; <condition>; <update>) {

<statement>; <statement>;

<statement>;

(37)

FOR

LOOPS

⦿

The initialization is usually just that (but

doesn’t have to be).

⦿

The update is usually an assignment, and

often a compound assignment.

⦿

Most common form: counting loop:

for (int i = 0; i < n; i++) { <some operation>

(38)

FOR

LOOPS

⦿

Order of execution:

1. Execute initialization

2. Test condition

3. If condition is false, skip to step 7

4. Execute the body of the loop

5. Execute the update

6. Return to step 2 (iterate)

7. Continue with the statement after the body

(39)

FOR

LOOPS

(40)

CONDITIONS

⦿ We have the following relational operators for comparing

values:

⦿ Note that "equal to" is a double equals!!

◼ What is single equals?

⦿ Avoid using == and != with double

== Equal to

!= Not equal to

> Greater than

< Less than

(41)

FOR

LOOPS

⦿ Exercise 1: Write a Java program to read in a String and an integer from the user, then print out the String the given number of times.

⦿ Exercise 2: Write a Java program to print out the factorial of an integer input by the user.

Recall that n! = n * (n-1) * (n-2) * … * 2 * 1

⦿ Exercise 3: Write a Java program to ask the user for a

(42)
(43)

NESTED

FOR

LOOPS

⦿

When we place a loop in the body of another

loop, it is called a nested loop

for (int i = 0; i < 5; i++) {

for (int j = 0; j < 10; j++) { System.out.print("*"); }

(44)

NESTED

FOR

LOOPS

⦿

In the previous example, the outer loops runs 5

times

⦿

The inner loop runs 10 times

for each time the

outer loop runs

(45)

for (int i = 0; i < 5; i++) {

for (int j = 0; i < 10; j++) { System.out.print("*"); }

System.out.println(); }

for (int i = 0; i < 5; i++) {

for (int j = 0; j < 10; i++) { System.out.print("*"); }

System.out.println(); }

(46)

NESTED LOOPS

⦿ Exercise 1: Write a program to produce the following using nested loops:

11111 22222 33333 44444 55555

⦿ Exercise 2: Write a program to produce the following using nested loops:

1 22 333 4444 55555

References

Related documents

monitoring, call recording, and call barging can allow managers to effectively monitor their team’s quality of customer service provided, ensuring that agents are well trained and

A file in the geocoding rule base that contains pattern rules and actions for standardizing an address and converting the recognized operands into match key fields. The file name

Write the greatest 5-digit number in figures and words.. By using all the digits given below, make the greatest and the smallest

Funkcija koju on daje sumnji ostaje ipak nejasna, jer to nešto što treba sačuvati može isto tako biti i nešto što treba pokazati — jer, u svakom slučaju to što se po­

except “Showtime” produced by Danja for Danja Handz Productions and “No Hay Igual” produced by Timbaland for Timbaland Productions, Danja for Danja Handz Productions and Nisan

For the detection of AMR determinants, the results were interpreted as follows: (i) a positive penA Asp345del reaction (indicating the presence of a mosaic penA allele) without or

This is really what is going at this time, that God is coming; it’s the message that’s He’s coming.. He’s going to instill fear on those who are

If the applicant does not provide the personal information required by the application form, NASC Investment may not be able to process the application or may take longer to