Transcript CS 177

Week 15 - Monday

  What did we talk about last time?

File I/O

 Let's write a program that prints the first million prime numbers to a file

    20% multiple choice questions 20% short answer questions 60% programming Designed to take 2 hours (50% longer than the previous exams)   But, you will have the full 3 hour time period More focus will be on the second half of the semester

     History of computers Hardware Software development Basic Java syntax Output with

System.out.print()

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

Cache

• Actually on the CPU • Fast and expensive

RAM

• Primary memory for a desktop computer • Pretty fast and relatively expensive

Flash Drive

Faster than hard drivesMost commonly on USB keychains

Hard Drive

• Secondary memory for a desktop computer • Slow and cheap

Optical Drive

• Secondary memory that can usually only be written once • Very slow and very cheap

  Storage for all the data and instructions on your computer Modern computers store everything as binary digits (bits) which have a value of 0 or 1.

1 byte 1 kilobyte (kb) 1 megabyte (mb) 1 gigabyte (gb) 1 terabyte (tb) = 8 bits = 2 10 bytes = 2 20 bytes = 2 30 bytes = 2 40 bytes

Monitor

• Common visual output device

Speakers

• Common audio output device

Mouse

• Common input device

Keyboard

• Common input device

Source Code Computer!

Solve a problem; Machine Code 010101010 010100101 001110010 Execute Hardware

Java Source Code class A { Problem p; p.solve(); } Java Bytecode 101110101 101011010 110010011 JVM Machine Code 010101010 010100101 001110010 Hardware

Often goes through phases similar to the following: 1.

Understand the problem 2.

3.

4.

Plan a solution to the problem Implement the solution in a programming language Test the solution 5.

Maintain the solution and do bug fixes

Factor of 10 rule!

 The absolute smallest program possible, with a print statement

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

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

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

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

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

Java generally ignores whitespace (tabs, newlines, and spaces)

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

is the same as:

System.out.

println( "Hello, world!" );

 You should use whitespace effectively to make your code readable

  There are two kinds of comments (actually 3) Single line comments use

// System.out.println( "Hi!" ); // this is a comment

 Multi-line comments start with a

/*

with a

*/

and end

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

   Binary representation Basic data types Using

Scanner

for input

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

1024’s Sixty fours 256’s Sixteens Fours 1 1 1 1 1 0 1 1 1 0 1 Ones 512’s 128’s Eights Thirty twos Twos

   We are going to focus 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 As you now know,

String

from the rest is a little different

Type int double boolean char String Kind of values

Integers Floating-point Numbers Boolean values Single characters Sequences of characters

Sample Literals -5 0 900031 3.14

-0.6

6.02e23

true false 'A' 'Z' '&' "If you dis Dr. Dre" "10 Sequipedalians"

  The

int

type is used to store integers (positive and negative whole numbers and zero) Examples:  54   -893992  0 Inside the computer, an

int

takes up 4 bytes of space, which is 32 bits (1's and 0's)

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

an

int

variable: variable is just like

double x = 1.28;

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

boolean

s now Declaration of a

boolean

variable is like so:

boolean value = false ;

    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 = 'L' ;

    The

String

type is different from the other types in several ways The important thing to focus on is that it can hold a large number of

char

values A

String

World program A

String

literal is what we used in the Hello, variable is declared much like any other type

String word = "Terrifying!" ;

There are three parts to using

Scanner

for input 1.

2.

3.

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

Scanner

object is Create a specific

Scanner

object with a name you choose Use the object you create to read in data

    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;

  Once you have imported the

Scanner

you have to create a

Scanner

class, 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:

Scanner in = new Scanner(System.in);

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

in

Hopefully this code makes more sense now

    Now that you've got a

Scanner

use it to read some data object, you can 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();

      Numerical operations Advanced math operations

boolean

operations

char

operations

String

operations Wrapper classes

   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 int Scanner(System.in); number = in.nextInt(); double radius = in.nextDouble(); String word = in.next();

    

+

adds

* /

multiplies divides (integer division for

int

fractional parts for

double

type)

%

subtracts finds the remainder type and

 Order of operations holds like in math

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

  You can use parentheses to clarify or change the precedence Now

a

is 16

int

You cannot directly store a

double

into an

int

variable

a = 2.6; // fails!

value 

int

However, you can cast the

double

convert it into an

int

value to

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

  Casting tells the compiler that you want the loss of precision to happen You can always store an

int

into a

double

    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 );

    In Java, the conversion of a

double int

does not use rounding into an As in the case of integer division, the value is always rounded down You can think of this as using the floor function from math If you want to round normally, you can simply add 0.5 before the cast

double x = 2.6; int a = ( int )(x + 0.5); // rounds

Return type double double Name sin( double theta ) cos( double theta ) double double double double long double double tan( double theta ) exp( double a ) log( double a ) pow( double a, double b ) round( double a ) random() sqrt( double a ) Job

Find the sine of angle theta Find the cosine of angle theta Find the tangent of angle theta Raise e to the power of a (e a ) Find the natural log of a Raise a to the power of b (a b ) Round a to the nearest integer Create a random number in [0, 1) Find the square root of a

  

!

NOT  Flips value of operand from

true

to

false

or vice versa

&&

AND 

true ||

OR if both operands are

true

 

^ true

if either operand is

true

XOR 

true

if operands are different

 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

char

values can be treated like an

int int number; number = 'a' ; // number contains 97

 It can be more useful to get the offset from a starting point

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

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

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

String

s is the

+

(concatenation) operator This operator creates a new

String

that is the concatenation of the two source

String

s Concatenation can be used to insert the values of other types into

String

s as well

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

    

equals()

 Tests two

String

s 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

 Each primitive data type in Java has a wrapper class 

Integer

▪ Allows

String

representations of integer values to be converted into

int

s  

Double

▪ Allows

String

representations of floating point values to be converted into

double

s

Character

▪ Provides methods to test if a

char

is lower case, is upper case ▪ value is a digit, is a letter, Provides methods to change a

char

lower case value to upper case or

 Making choices with if statements  Basics  Having if bodies with more than one line  Using else blocks   Nesting if statements Using

switch

statements

The

if

part Any

boolean

expression

if( condition ) statement;

Any single executable statement

if( condition ) statement1; else statement2;

Two different outcomes

if( condition ) { statement1;

A whole bunch of statements

statement2; … statementn; }

if( condition1 ) { statement1;

if( condition2 ) { if( condition3 ) statement2; … }

}

  The most common condition you will find in an

if

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

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

int data = 3;

Both

"Three" switch ( data ) { case

and

3: System.out.println( "Three" ); "Four"

are printed

case 4: } case

The

System.out.println( "Four" ); break ; 5: System.out.println( "Five" ); default

The

break

is is optional too optional

1.

2.

3.

4.

5.

6.

The data that you are performing your

switch

on must be either an

int

, a

char

, or a

String

The value for each

case

must be a literal Execution will jump to the

case

that matches If no

case

matches, it will go to

default

If there is no

default

, it will skip the whole

switch

block Execution will continue until it hits a

break

  Review up to Exam 2 IDEA forms  Bring a #2 pencil

 

Keep working on Project 5

Due on Friday before midnight Study for Final Exam

11:00am - 2:00pm, Friday, 12/12/2014