Week 1 -Wednesday What did we talk about last time? Syllabus - - PowerPoint PPT Presentation

week 1 wednesday what did we talk about last time
SMART_READER_LITE
LIVE PREVIEW

Week 1 -Wednesday What did we talk about last time? Syllabus - - PowerPoint PPT Presentation

Week 1 -Wednesday What did we talk about last time? Syllabus Course policies Java basics In Java, every variable and every literal has a type A type says what kind of data it is In Python, you could just assign a value to


slide-1
SLIDE 1

Week 1 -Wednesday

slide-2
SLIDE 2

 What did we talk about last time?  Syllabus  Course policies  Java basics

slide-3
SLIDE 3
slide-4
SLIDE 4
slide-5
SLIDE 5

 In Java, every variable and every literal has a type  A type says what kind of data it is  In Python, you could just assign a value to a variable  In Java, every variable must be declared with its type before you

use it:

 Java is also strongly typed, meaning that type errors will prevent

your program from compiling

double x;

int y = 4.0; //illegal, since 4.0 is a double

slide-6
SLIDE 6

 Five basic types of data in Java let you get most things done  These are:

  • int

For whole numbers

  • double

For rational numbers

  • boolean

For true or false values

  • char

For single characters

  • String

For words

 String is a little different from the rest, since you can call

methods on it (and for other reasons)

 There are also byte, short, and long versions of int, which

use 1, 2, and 8 bytes, respectively

slide-7
SLIDE 7

Type Kind of values Sample Literals int

Integers

  • 5

900031

double

Floating-point Numbers

3.14

  • 0.6

6.02e23

boolean

Boolean values

true false

char

Single characters

'A' 'Z' '&'

String

Sequences of characters

"If you dis Dr. Dre" "10 Sesquipedalians"

slide-8
SLIDE 8

 The int type is used to store integers (positive and negative

whole numbers and zero)

 Examples:

  • 54
  • -893992

 Inside the computer, an int takes up 4 bytes of space, which

is 32 bits (1's and 0's)

slide-9
SLIDE 9

 You will use the int type very often  Sometimes, however, you need to represent numbers with a

fractional part

 The double type is well suited to this purpose  Declaration of a double variable is just like an int variable:

double x;

slide-10
SLIDE 10

 Numbers are great  But, sometimes you only need to keep track of whether or not

something is true or false

 This is what the boolean type is for  Hopefully you have more appreciation for booleans now  Declaration of a boolean variable is like so:

boolean value;

slide-11
SLIDE 11

 Sometimes you need to deal with characters  This is what the char type is for  The char type only allows you to store a single character like

'$' or 'q'

 Declaration of a char variable is like so:

char c;

slide-12
SLIDE 12

 The String type is different from the other types in several

ways

 The important thing for you to focus on now is that it can hold

a large number of chars, not just a single value

 A String literal is what we used in the Hello, World program

String word;

slide-13
SLIDE 13

There are three parts to using Scanner for input

1.

Include the appropriate import statement so that your program knows what a Scanner object is

  • 2. Create a specific Scanner object with a name you choose

3.

Use the object you create to read in data

slide-14
SLIDE 14

 Lots of people have written all kinds of useful Java code  By importing that code, we can use it to help solve our

problems

 To import code, you type import and then the name of the

package or class

 To import Scanner, type the following at the top of your

program (before the class!) import java.util.Scanner;

slide-15
SLIDE 15

 Once you have imported the Scanner class, you have to

create a Scanner object

 To do so, declare a reference of type Scanner, and use the

new keyword to create a new Scanner with System.in as a parameter like so:

 You can call it whatever you want, I chose to call it in

Scanner in = new Scanner(System.in);

slide-16
SLIDE 16

 Now that you've got a Scanner object, you can use it to read

some data

 It has a method that will read in the next piece of data that

user types in, but you have to know if that data is going to be an int, a double, or a String

 Let's say the user is going to input her age (an int) and you

want to store it in an int variable called years

 We'll use the nextInt() method to do so:

int years; years = in.nextInt();

slide-17
SLIDE 17

 Scanner has a lot of methods (ways to accomplish some tasks)  For now, we're only interested in three  These allow us to read the next int, the next double, and

the next String, respectively:

Scanner in = new Scanner(System.in); int number = in.nextInt(); double radius = in.nextDouble(); String word = in.next();

slide-18
SLIDE 18

 + adds  - subtracts  * multiplies  / divides (integer division for int type and fractional parts for

double type)

 % finds the remainder

slide-19
SLIDE 19

Return type Name Job double sin( double theta ) Find the sine of angle theta double cos( double theta ) Find the cosine of angle theta double tan( double theta ) Find the tangent of angle theta double exp( double a ) Raise e to the power of a (ea) double log( double a ) Find the natural log of a double pow( double a, double b ) Raise a to the power of b (ab) long round( double a ) Round a to the nearest integer double random() Create a random number in [0, 1) double sqrt( double a ) Find the square root of a double toDegrees( double radians ) Convert radians to degrees double toRadians( double degrees ) Convert degrees to radians

slide-20
SLIDE 20

 ! NOT

  • Flips value of operand from true to false or vice versa

 && AND

  • true if both operands are true

 || OR

  • true if either operand is true

 ^ XOR

  • true if operands are different
slide-21
SLIDE 21

 In some circumstances, Java doesn't check the whole

expression:

 (true || (some complicated expression))

  • Ignores everything after || and gives back true

 (false && (some complicated expression))

  • Ignores everything after && and gives back false
slide-22
SLIDE 22

 char values can be treated like an int  It can be more useful to get the offset from a starting point

int number; number = 'a'; // number contains 97 char letter = 'r'; int number; number = letter – 'a' + 1; //number is 18

slide-23
SLIDE 23

 We use single quotes to designate a char literal: 'z'  What if you want to use the apostrophe character ( ' )?

  • apostrophe:

'\''

 What if you want to use characters that can't be printed, like tab

  • r newline?
  • tab:

'\t'

  • newline:

'\n'

 The backslash is a message that a special command called an

escape sequence is coming

 These can be used in String literals as well:

  • "\t\t\t\nThey said, \"Wow!\""
slide-24
SLIDE 24

 The only operator that we will use directly with Strings is

the + (concatenation) operator

 This operator creates a new String that is the

concatenation of the two source Strings

 Concatenation can be used to insert the values of other types

into Strings as well

String word; word = "tick" + "tock"; // word is "ticktock"

slide-25
SLIDE 25

 equals()

  • Tests two Strings to see if they are the same

 compareTo()

  • Returns a negative number if the first String comes earlier in the alphabet, a

positive number if the first String comes later in the alphabet, and 0 if they are the same

 length()

  • Returns the length of the String

 charAt()

  • Returns the character at a particular index inside the String

 substring()

  • Returns a new String made up of the characters that start at the first index

and go up to but do not include the second index

slide-26
SLIDE 26

 Each primitive data type in Java has a wrapper class

  • Integer

▪ Allows String representations of integer values to be converted into ints

  • Double

▪ Allows String representations of floating point values to be converted into doubles

  • Character

▪ Provides methods to test if a char value is a digit, is a letter, is lower case, is upper case ▪ Provides methods to change a char value to upper case or lower case

slide-27
SLIDE 27
slide-28
SLIDE 28

 The if-statement:  x is small will only print out if x is less than 5  In this case, we know that it is, but x could come from user

input or a file or elsewhere

int x = 4; if( x < 5 ) System.out.println("x is small!");

slide-29
SLIDE 29

The if part Any boolean expression Any single executable statement

if( condition ) statement;

slide-30
SLIDE 30
slide-31
SLIDE 31

 Any statement that evaluates to a boolean is legal  Examples:

  • x == y
  • true
  • Character.isDigit('r')
  • s.equals("Help me!") && (z < 4)
slide-32
SLIDE 32

 The most common condition you will find is a comparison

between two things

 In Java, that comparison can be:

  • ==

equals

  • !=

does not equal

  • <

less than

  • <=

less than or equal to

  • >

greater than

  • >=

greater than or equal to

 These are called relational operators

slide-33
SLIDE 33

 You can use the == operator to compare any two things of the

same type

 Different numerical types can be compared as well (3 ==

3.0)

 Be careful with double types, 0.33333333 is not equal to

0.33333332

int x = 3; if( x == 4 ) System.out.println("This doesn't print");

slide-34
SLIDE 34

 Any place you could have used the == operator, you can use

the != operator

 If == gives true, the != operator will always give false, and

vice versa

 If you want to negate a condition, you can always use the ! as

a not is the same as

if( x != 4 ) if( !(x == 4) )

slide-35
SLIDE 35

 Remember, a single equal sign (=) is the assignment operator

(think of a left-pointing arrow)

 A double equals (==) is a comparison operator

int y = 10; if( y = 6 ) //compiler error! boolean b = false; if( b = false ) //no compiler error but wrong

slide-36
SLIDE 36

 Inequality is very important in programming  You may want to take an action as long as a value is below a

certain threshold

 For example, you might want to keep bidding at an auction

until the price is greater than what you can afford

 Watch for strict inequality (<) vs. non-strict inequality (<=)

if( x <= 4 ) System.out.println("x is less than 5");

slide-37
SLIDE 37

 Just like less than or equal to, except the opposite  Note that (because of the All-Powerful Math Gods) the

  • pposite of <= is > and the opposite of >= is <

 Thus,

  • !( x <= y ) is equivalent to ( x > y )
  • !( x >= y ) is equivalent to ( x < y )
slide-38
SLIDE 38
slide-39
SLIDE 39

 Sometimes you have to make a decision  If a condition is true, you go one way, if not, you go the other  For example:

  • If I pass COMP 2100,

▪ Then I throw a kegger to celebrate

  • Otherwise,

▪ I punch Dr. Wittman in the face

slide-40
SLIDE 40

 Notice the nature of this kind of condition  Both outcomes cannot happen  Either a kegger gets thrown or Dr. Wittman gets punched in

the face

 For these situations, we use the else construct

slide-41
SLIDE 41

Two different

  • utcomes

if( condition ) statement1; else statement2;

slide-42
SLIDE 42

Scanner in = new Scanner(System.in); int balance = in.nextInt(); if( balance < 0 ) System.out.println("You are in debt!"); else System.out.println("You have $" + balance);

slide-43
SLIDE 43
slide-44
SLIDE 44

 No problem  Use braces to treat a group of statements like a single

statement

if( x == 4 ) { System.out.println("I hate 4"); System.out.println("Let's change x."); x = 10; }

slide-45
SLIDE 45

if( condition ){ statement1; statement2; … statementn; }

A whole bunch of statements

slide-46
SLIDE 46

 Sometimes you want to make one set of decisions based on

another set of decisions

 if-statements can be nested inside the bodies of other if-

statements

 You can put if-statements inside of if-statements inside of

if-statements… going arbitrarily deep

slide-47
SLIDE 47

if( condition1 ){ statement1;

if( condition2 ) {

if( condition3 ) statement2; …

}

}

slide-48
SLIDE 48

 For the next example, recall the 4 quadrants of the Cartesian

coordinate system

x

  • x

y

  • y

(0,0) 1

2 3 4

slide-49
SLIDE 49

 Find which quadrant the point (x,y) is in

if( x >= 0.0 ) { if( y >= 0.0 ) System.out.println("Quadrant 1"); else System.out.println("Quadrant 4"); } else { if( y >= 0.0 ) System.out.println("Quadrant 2"); else System.out.println("Quadrant 3"); }

slide-50
SLIDE 50

 You can list a sequence of exclusive possibilities using nesting:

if( index == 1 ) System.out.println("First"); else if( index == 2 ) System.out.println("Second"); else if( index == 3 ) System.out.println("Third"); else System.out.println(index + "th");

slide-51
SLIDE 51

 A block of code is treated just like one statement  A whole if-else is treated the same

if( … ) statement1; else if( … ) statement2; else statement3; if( … ) { statement1; } else { if( … ) statement2; else statement3; }

=

slide-52
SLIDE 52
slide-53
SLIDE 53

 Assume that you have a variable called base of type char  Let base contain one of: 'A', 'C', 'G', 'T'  Write a series of if- and else-statements that will print out

the chemical name of the base denoted by the corresponding character

  • A -> Adenine
  • C -> Cytosine
  • G -> Guanine
  • T -> Thymine
slide-54
SLIDE 54

if( base == 'A' ) System.out.println("Adenine"); else if( base == 'C' ) System.out.println("Cytosine"); else if( base == 'G' ) System.out.println("Guanine"); else if( base == 'T' ) System.out.println("Thymine"); else System.out.println("Your base doesn't belong to us");

 What if you want to take care of upper and lower cases?

slide-55
SLIDE 55

 Is there a simpler way?

if( base == 'A' || base == 'a' ) System.out.println("Adenine"); else if( base == 'C' || base == 'c' ) System.out.println("Cytosine"); else if( base == 'G' || base == 'g' ) System.out.println("Guanine"); else if( base == 'T' || base == 't' ) System.out.println("Thymine"); else System.out.println("Your base doesn't belong to us");

slide-56
SLIDE 56

base = Character.toUpperCase( base ); if( base == 'A' ) System.out.println("Adenine"); else if( base == 'C' ) System.out.println("Cytosine"); else if( base == 'G' ) System.out.println("Guanine"); else if( base == 'T' ) System.out.println("Thymine"); else System.out.println("Your base doesn't belong to us");

slide-57
SLIDE 57
slide-58
SLIDE 58

 But, didn't that DNA example seem a little clunky?  Surely, there's a cleaner way to express a list of possibilities  Enter: the switch statement

slide-59
SLIDE 59

switch( data ) { case value1: statements 1; case value2: statements 2; … case valuen: statements n; default: default statements; }

slide-60
SLIDE 60

switch( base ) { case 'A': System.out.println("Adenine"); break; case 'C': System.out.println("Cytosine"); break; case 'G': System.out.println("Guanine"); break; case 'T': System.out.println("Thymine"); break; default: System.out.println("Your base" + "doesn't belong to us"); break; // unnecessary }

slide-61
SLIDE 61

int data = 3; switch( data ) { case 3: System.out.println("Three"); case 4: System.out.println("Four"); break; case 5: System.out.println("Five"); }

Both "Three" and "Four" are printed The break is

  • ptional

The default is optional too

slide-62
SLIDE 62
  • 1. The data that you are performing your switch on must be

an int, a char, or a String

  • 2. The value for each case must be a literal
  • 3. Execution will jump to the case that matches
  • 4. If no case matches, it will go to default
  • 5. If there is no default, it will skip the whole switch block
  • 6. Execution will continue until it hits a break
slide-63
SLIDE 63

switch( base ) { case 'A': case 'a': System.out.println("Adenine"); break; case 'C': case 'c': System.out.println("Cytosine"); break; case 'G': case 'g': System.out.println("Guanine"); break; case 'T': case 't': System.out.println("Thymine"); break; default: System.out.println("Your base doesn't belong to us"); break; // unnecessary }

slide-64
SLIDE 64

 Using if-statements is usually safer  if-statements are generally clearer and more flexible  switch statements are only for long lists of specific cases  Be careful about inconsistent use of break

slide-65
SLIDE 65
slide-66
SLIDE 66

 Lab 2 is tomorrow  Next lecture:

  • Loops
  • Arrays
  • Methods
  • File I/O
slide-67
SLIDE 67

 Keep reading 1.1 of Algorithms  Consider reading Chapters 5, 6, and 8 from https://start-

concurrent.github.io/