302 lecture 1

Upload: bob-williams

Post on 06-Apr-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 302 Lecture 1

    1/12

    302 Chapter 1 1/26/2012 2:05:00 PM

    Algorithms

    y What is an algorithm?o A recipe for finding a solutiono The steps that describe how to solve a problemo A detailed list of instructions that, when followed, result

    Algorithms-Basics

    y Algorithms must beo Unambiguous

    Instructions must precisely say what to do for each stepand where to go next

    o Executable Can be carried out in practice

    o Terminating Must eventually come to an end

    y The language we use to specify instructions should be precise andunambiguous (a formal language)

    Languages

    y Natural languages-languages humans use to communicate, and arefull of ambiguity

    y Formal languages precise and unambiguous languages used tocommunicate specific ideas

    Algorithms- Executiony An algorithm transforms an initial states into some final state after

    executing a sequence of operations.

    Algorithms-Basics

    y How do we determine if an algorithm works as desired?o We carefully perform the algorithm to see what results. It

    works if we get the desired outcome

    Algorithms-Execution

    y What do we assume will happen when someone executes ouralgorithm?

    o We start at the beginning, topo In order from top to bottom sequencingo They will stop at bottom

    Algorithms-Criteria

    y What makes an algorithm good?

  • 8/3/2019 302 Lecture 1

    2/12

    o it works as desiredo it is efficient (takes fewer steps)o it is robust (handles errors well)o it is user friendlyo it is clear(well-structure, well-documented)o it is general

    Write a Java program that says hello world.

    public class HelloWorld {

    public static void main(string[] args) {

    system.out.println(Hello World!)

    }

    }

    Whats a class?

    y Its a container for programs codey Whats the name of the class?

    o Hello Worldy Start class names with an uppercase letter

    Whats a file?

    y Its a container of related info thats kept in secondary storageWhats a method?

    y Its a container for instructions that do a particular tasks or solve aparticular part of the problem

    y Java programs begin executing at first instruction in the mainmethod and stop at the last instruction in main.

    Whats a statement?

    y Its an instruction! There are many different kinds of statementsand they end in a semicolon;

    What does system.out.println do?

    y It displays whats between the parenthesis.y Println follows the output with a new line, where as print does not.

    Developing

    y We use Eclipse to make programs:o Editing: entering text into a source file (.java)o Compiling: translating the source file into a class file (.class)o Running: using the JVM to execute the class file.

    Commenting

  • 8/3/2019 302 Lecture 1

    3/12

    y /* multilinecomment*/

    y //single line commenty Comments make programs more understandable, but are ignored

    by the compiler.Braces

    y What are Braces used for?o Recall a class and a method are containers. Braces make the

    beginning and end of these containers.

    Body: whats between {} Heading: what comes before {

    o Make sure every opening brace { has a matching } bracey What is a reserved word?

    o Its a word defined by the ? to have a specific purposeo Reserved words: Public static void classo Reserved words cannot be used for naming things

    y What is an identifier?o Its a name we give to a class, a method, a variable, etc.o Identifiers: class-IRemember String Systemo Methods: main printlno Variables: args out

    y When choosing identifiers naming rules must be followed.Naming Rules

    y Identifiers consist of only letters (a-z, A-Z)y Digits(0-9) and _ charactersy Reserved words cannot be used.

    Naming Conventions

    y use meaningful/descriptive namesy variable and method names begin with a lowercase lettery class name begin with an uppercase letter.y Use camel case for multiword namesy CONSTANT names are all in UPPERCASE and we separate with (_)

  • 8/3/2019 302 Lecture 1

    4/12

    302 Chapter 2 1/26/2012 2:05:00 PM

    Variables

    Whats a variable?

    y Its a container for a single value that can change. It can store onlyone particular type of data.

    How does a computer know the variables type?

    y Before a variable can be used, its type is specified in a declarationstatement. The form is :

    y ;By convention, we put variable declaration statements at the beginning of a

    method.

    Numeric Data Types

    If a variable holds a whole number, what type should be used?

    y Int if the range of values is 2 billion to + 2 billiony We call these integers

    If a variable holds a real number, what type should be used?

    y Double if the range of values is 3.4*10^308 to + 3.4*10^308y We call these floating-point numbers

    There are other numeric data types, but for now well use these.

    Variables

    How is a variable given a value?

    y Either by initializing it in the declaration statement or by using anassignment statement.

    When reading assignment statement replace the = with the word gets. For

    Example:

    y Month = 12;y month GETS 12

    Assignment Statements

    Form of the Assignment Statement:

    y = ;y LHS of = is a variable

  • 8/3/2019 302 Lecture 1

    5/12

    y RHS of = can beo A literal value: count = 112233;o A variable: count = numberOfStudentso An expression count = count + 1;

    y Commas are not NOT allowed in numbers! 112,233 results in acompile-time error.

    y Tracing assignment statements:o 1. First figure out the value of the result on the righto 2. Then assign that value to the variable on the left

    Mixing Numeric Types

    y Assigning an integer value into a floating-point variable works justfine:

    o Double accountBalence = 1000;y Assigning a floating-point value into an integer variable does NOT

    work!

    o Int numberOfStudents = 22.11; Why? Its like trying to cram a large object into a small

    box. It doesnt fit and thats illegal.

    To do this you must use a type cast: Int numberOfStudent = (int) 22.11;

    Constants

    y Whats a constant?o Its a single value that CANNOT change ( during execution). It

    can either be an explicit value ( called a liter or hard-coded

    constant), or it can be a named constant (just called a

    constant).

    y Use named constants to make your program more understandableand easier to update/correct!

    y Write server examples of literal constantso Integer constants 11,2121212, -2o Floating-point 2.333o String constants string, howdy

    y final double INTEREST_RATE = .032;y Call named constants use the final modifier, which tells the compiler

    this is the final value it gets and any attempt to give it another

    results in a compile-time error!

  • 8/3/2019 302 Lecture 1

    6/12

    Expressions

    y Whats and expression?o Its a combination of operators and operands that is evaluated

    to obtain a result value.

    y Whats an operator?o Its a symbol (+,-,*) that instructs the computer to perform a

    basic action on one or more operands.

    y Whats an operand?o Its a literal, constant, variable, results from another

    expression, a value returned by a method, or other source of

    information to be processed.

    Basic Arithmetic Operators

    y Basic mathematical operations are defined for integer and floating-point types including:

    o Binary operationso +o *o divisiono %remainder division

    y Division depends on the type of operands!y What do the following expression evaluate to?y Floating point 11/2.0= 5.5y 11/2 = 5y 11/0.0 error!y Integers also have remainder division (%modulous):

    o 11%2=1o 10%20= 10o 11%4 = 3

    increment and Decrement Operators

    y adding or subtracting by 1 are common operations;o count = count +1; // incremento count count -1; //incremento instead use these (unary) operators:o count++;o count--;

  • 8/3/2019 302 Lecture 1

    7/12

    y use ++ and - in statements by themselves ( as shown) to avoidconfusing results

    y Updating a variable based on its original value is another commonoperation:

    o X= x +11 X += 11; additionImprovements

    y How could our CylinderVolume program be improved?y Remove the hardcoded values for radius and height?y Make your program more General.y Algorithms for calculating programs

    o Get inputo Calculate the resulto Output the result

    The Scanner Class

    y Java provides a pre-written class named Scanner, which allows youto get input from a user.

    y Three things need to use pre-written classes:o 1.Find it! Tell the compiler where to get the code us using an

    import statement:

    Import java.util.Scanner;o 2. Make it! Make a software object by declaring an initializing:

    Scanner stdIn = new Scanner(System.in);o 3. Use it! Use the software object by calling its methods:

    = stdIn.nextInt(); = stdIn.nextLine();

    Character Type- char

    y A char variable holds a single character (stored as an integervalue).

    y A char literal is surrounded by single quotes, for example: B, 1,:

    Escape Sequences

    y How do you print a ? System.out.println();o Not-o Its a compiler error! You much use escape sequences:o System.out.println(\);

    y Common escape sequences

  • 8/3/2019 302 Lecture 1

    8/12

    o \ for a double quoteo \ for a single quoteo \n for newline go to first column in next lineo \t to move cursor to the next tab stopo \\ for a backslash

    y use tabs /t to do organize outputString Class

    y String is another pre-written class from which we can makesoftware objects (Simply called objects). It does the work of storing

    and doing tasks on sequences of characters such as words,

    phrases, etc.

    y Software objects make programmer more efficient!y To use Strings:

    o 1.Find it? Not needed since this is automatically imported: import java.lang.String;

    o 2. Make it! Make String objects: String name1= Deb; String name2 = new String (Jim);

    o 3. Use it! Ask String objects to do tasks: name1.charAt (0)Using String Cass

    y String operations:o Assignment and initialization using =o Concatenation using +

    y String Methodso By calling methods we can do many useful things with Strings

    length: returns the number of characters in the stringobject

    String name = Elmer Fudd; System.out.print( name.length() + letters); Output: 10 letters

    Charat: returns the character at the specified position System.out.println(name.charAt(6) ); Output: F

    Primitive vs. Reference Variables

    y Java has two distinct categories of variables:

  • 8/3/2019 302 Lecture 1

    9/12

    o Primitive variables: store one value of a basic type Int age Double rate; Char myInitial;

    o Reference variables: store an address that says where to findits software object elsewhere in memory (more later)

    Scanner consoleIn = new Scanner (System.in); String name= Jim

    y Note reference types are Java class names.y To ask objects to do a task we use this form:

    o . ()Power of programming

    y Achieving the full power of programming requires being able tocontrol the flow of execution.

    y There are 3 ways the flow of execution is controlled:o Sequencing (AKA: Stepping)

    Doing one thing after another from start to finisho Deciding (AKA: Selecting, Branching, Ch.3)

    Doing something when a condition is trueo Looping (AKA: Repeating, Ch. 4)

    Doing something again and again as long as a conditionremains true.

  • 8/3/2019 302 Lecture 1

    10/12

    302 Chapter 3 1/26/2012 2:05:00 PM

    ifIntro

    y We make decision in a program with if statements:o From if () {o o }

    y The condition will give a true/false resulty And execution depends on this result

    o True: do the statement(s)o False: skip over them do none!

    y Use an if statement when you wan to do one or none.If (year >= 2012)

    {

    System.out.println(This is not in the past);

    }

    else

    {

    System.out.println ( This year is in the past);

    }

    Comparison Pps: == != = >

    y one or noney Use if-else to do One or anothery Use if-else-if for one of many decisionsy The number of choices in your decision determines which for of if to

    use.

    if (year == 2012)

    {

    y System.out.println( The current year is + year);}

    else if (year > 2012)

    {

    y System.out.println( year + is in the future);}

    else

    {

    y System.out.println( year + is in the past);}

  • 8/3/2019 302 Lecture 1

    11/12

    Good Programs

    y What makes a program good?y Robusty User friendlyy Generaly Terminatingy Efficienty Clear( well structured, well documented)y What makes a program general?

    o When it can produce the final (desired) state from manyinitial states

    y General programs need to be able to decide which statements to dobased on the current state of the problem.

    y End with else only when there is 1 possibility lefty End with else if when there are more possibilities left that youre

    not considering.

    y ELSEIFWILL NOT DO ANYTHING IFIFIS ALREADY EXECUTEDy Is our solution robust?y Nesting is when you put one statement in the body of another as in

    this example which puts an if statements inside of if statements.y Use nesting to solve problems requiring multiple levels of decisions.

    Ball move problem 2

    y What are the constrains of our solutions?o 1. There must be one green ball and one rainbow ball.o 2. There must be only 3 cups numbered 1 to 3.

    y Preconditions specify what must initially be true for the solution towork!

    y A more GENERAL program has fewer preconditions, but it will needto make more complicated decisions!

    If (month= 2)

    {

    System.out.println( February had 28 days);

    }

    else if (month =

  • 8/3/2019 302 Lecture 1

    12/12