Week 4 - Friday What did we talk about last time? Examples switch - - PowerPoint PPT Presentation

week 4 friday what did we talk about last time examples
SMART_READER_LITE
LIVE PREVIEW

Week 4 - Friday What did we talk about last time? Examples switch - - PowerPoint PPT Presentation

Week 4 - Friday What did we talk about last time? Examples switch statements Format: Multiple choice questions (~20%) Short answer questions (~20%) Programming problems (~60%) On Blackboard during class time No


slide-1
SLIDE 1

Week 4 - Friday

slide-2
SLIDE 2

 What did we talk about last time?  Examples  switch statements

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

 Format:

  • Multiple choice questions (~20%)
  • Short answer questions (~20%)
  • Programming problems (~60%)

 On Blackboard during class time

  • No notes
  • Closed book
  • No calculator
slide-7
SLIDE 7

 History of computers  Hardware  Software development  Basic Java syntax  Output with System.out.print()

slide-8
SLIDE 8

Mechanical Calculation Devices (2400BC onward)

  • Aid to human calculation
  • No stored program

Mechanical Computers (1725 onward)

  • Punch card programming
  • Serious limitations

Early Electronic Computers (1941 onward)

  • General purpose, stored program computers
  • Electronic, using vacuum tubes

Microprocessors (1970's onward)

  • Succeeded transistors
  • Now billions of computations per second at a nanometer scale
slide-9
SLIDE 9

Often goes through phases similar to the following:

  • 1. Understand the problem
  • 2. Plan a solution to the problem
  • 3. Implement the solution in a programming language
  • 4. Test the solution
  • 5. Maintain the solution and do bug fixes

Factor of 10 rule!

slide-10
SLIDE 10

Computer! Solve a problem; 010101010 010100101 001110010

Execute

Source Code Machine Code Hardware

slide-11
SLIDE 11

class A { Problem p; p.solve(); } 101110101 101011010 110010011

JVM

010101010 010100101 001110010

Java Source Code Machine Code Hardware Java Bytecode

slide-12
SLIDE 12

 The absolute smallest program possible, with a print

statement public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } }

slide-13
SLIDE 13

 For example, instead of one print statement, we can have

several:

 Each statement is an instruction to the computer  They are printed in order, one by one

System.out.println("Hello, world!"); System.out.println("Hello, galaxy!"); System.out.println("Goodbye, world!");

slide-14
SLIDE 14

 Java is a case sensitive language  Class is not the same as class  System.out.println("Word!"); prints correctly  system.Out.Println("Word!"); does not compile

slide-15
SLIDE 15

 Java generally ignores whitespace (tabs, newlines, and spaces)  is the same as:  You should use whitespace effectively to make your code readable

System.out.println("Hello, world!"); System.out. println( "Hello, world!");

slide-16
SLIDE 16

 There are two kinds of comments (actually 3)  Single line comments use //  Multi-line comments start with a /* and end with a */

System.out.println("Hi!"); // this is a comment System.out.println("Hi!"); /* this is a multi-line comment */

slide-17
SLIDE 17

 Binary representation  Basic data types  Using Scanner for input  Numerical operations

slide-18
SLIDE 18

 The binary number system is base 2  This means that its digits are: 0 and 1  Base 2 means that you need 2 digits to represent two, namely

1 and 0

 Each place in the number as you move left corresponds to an

increase by a factor of 2 instead of 10

slide-19
SLIDE 19

11111100100

Ones 1024's Sixteens Thirty twos Eights Sixty fours Twos Fours 256's 128's 512's

slide-20
SLIDE 20

 We're focusing on five basic types of data in Java  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)

slide-21
SLIDE 21

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-22
SLIDE 22

 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-23
SLIDE 23

 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-24
SLIDE 24

 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-25
SLIDE 25

 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-26
SLIDE 26

 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-27
SLIDE 27

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-28
SLIDE 28

 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-29
SLIDE 29

 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-30
SLIDE 30

 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 = in.nextInt();

slide-31
SLIDE 31

 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-32
SLIDE 32

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

double type)

 % finds the remainder

slide-33
SLIDE 33

 Order of operations holds like in math  You can use parentheses to clarify or change the precedence  Now a is 16

int a = 31; int b = 16; int c = 1; int d = 2; a = (((b + c) * d) – a / b) / d;

slide-34
SLIDE 34

 You cannot directly store a double value into an int

variable

 However, you can cast the double value to convert it into an

int

 Casting tells the compiler that you want the loss of precision

to happen

 You can always store an int into a double

int a = 2.6; // fails! int a = (int)2.6;// succeeds! (a = 2)

slide-35
SLIDE 35

 Advanced math operations  boolean operations  char operations  String operations  Wrapper classes

slide-36
SLIDE 36

 The sin() method allows you to find the sine of an angle (in

radians)

 This method is inside the Math class  The answer that it gives back is of type double  To use it, you might type the following:

double value = Math.sin( 2.4 );

slide-37
SLIDE 37

 In Java, the conversion of a double into an int does not use

rounding

 As in the case of integer division, the fractional part is

dropped

 For positive numbers, that's like using floor  For negative numbers, that's like using ceiling  The right way to do rounding is to call Math.round()

double x = 2.6; int a = (int)Math.round(x); // rounds

slide-38
SLIDE 38

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-39
SLIDE 39

 ! 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-40
SLIDE 40

 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-41
SLIDE 41

 Remember that 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 or

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-42
SLIDE 42

 The main operator 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

  • ther types into Strings as well

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

slide-43
SLIDE 43

 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-44
SLIDE 44

 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-45
SLIDE 45

 Making choices with if statements

  • Basics
  • Using else blocks
  • Nesting if statements

 Using switch statements

slide-46
SLIDE 46

The if part Any boolean expression Executable statements

if( condition ){ statements; }

slide-47
SLIDE 47

Two different

  • utcomes

if( condition ) { statements1; } else { statements2; }

slide-48
SLIDE 48

if( condition1 ){ statement1;

if( condition2 ) {

if( condition3 ) statement2; …

}

}

slide-49
SLIDE 49

 The most common condition you will find in an if is a

comparison between two primitive types

 In Java, that comparison can be:

  • ==

equals

  • !=

does not equal

  • <

less than

  • <=

less than or equal to

  • >

greater than

  • >=

greater than or equal to

slide-50
SLIDE 50

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

slide-51
SLIDE 51

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-52
SLIDE 52
  • 1. The data that you are performing your switch on must be

either 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-53
SLIDE 53
slide-54
SLIDE 54

 Exam 1

slide-55
SLIDE 55

 Study for Exam 1

  • Monday, online, during class time

 Keep working on Project 2