You are on page 1of 12

302 Chapter 1

1/26/2012 2:05:00 PM

Algorithms y What is an algorithm? o A recipe for finding a solution o The steps that describe how to solve a problem o A detailed list of instructions that, when followed, result Algorithms-Basics y Algorithms must be o Unambiguous  Instructions must precisely say what to do for each step and 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 and unambiguous (a formal language) Languages y Natural languages-languages humans use to communicate, and are full of ambiguity y Formal languages precise and unambiguous languages used to communicate specific ideas Algorithms- Execution y 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 our algorithm? o We start at the beginning, top o In order from top to bottom sequencing o They will stop at bottom Algorithms-Criteria y What makes an algorithm good?

o it works as desired o it is efficient (takes fewer steps) o it is robust (handles errors well) o it is user friendly o 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 code y Whats the name of the class? o Hello World y Start class names with an uppercase letter Whats a file? y Its a container of related info thats kept in secondary storage Whats a method? y Its a container for instructions that do a particular tasks or solve a particular part of the problem y Java programs begin executing at first instruction in the main method and stop at the last instruction in main. Whats a statement? y Its an instruction! There are many different kinds of statements and 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

/* multiline comment*/ y //single line comment y 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 } brace y What is a reserved word? o Its a word defined by the ? to have a specific purpose o Reserved words: Public static void class o 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 System o Methods: main println o 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 _ characters y Reserved words cannot be used. Naming Conventions y use meaningful/descriptive names y variable and method names begin with a lowercase letter y class name begin with an uppercase letter. y Use camel case for multiword names y CONSTANT names are all in UPPERCASE and we separate with (_) y

302 Chapter 2
Variables

1/26/2012 2:05:00 PM

Whats a variable? y Its a container for a single value that can change. It can store only one 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 declaration statement. The form is : y <Type> <list of variables separated by commas>; 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 billion y 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^308 y 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 an assignment 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 <variable> = <value, variable, or expression>; y LHS of = is a variable

RHS of = can be o A literal value: count = 112233; o A variable: count = numberOfStudents o An expression count = count + 1; y Commas are not NOT allowed in numbers! 112,233 results in a compile-time error. y Tracing assignment statements: o 1. First figure out the value of the result on the right o 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 just fine: 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 understandable and easier to update/correct! y Write server examples of literal constants o Integer constants 11,2121212, -2 o Floating-point 2.333 o 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! y

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 floatingpoint types including: o Binary operations o + o * o division o %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.5 y 11/2 = 5 y 11/0.0 error! y Integers also have remainder division (%modulous): o 11%2=1 o 10%20= 10 o 11%4 = 3 increment and Decrement Operators y adding or subtracting by 1 are common operations; o count = count +1; // increment o count count -1; //increment o instead use these (unary) operators: o count++; o count--;

use ++ and - in statements by themselves ( as shown) to avoid confusing results y Updating a variable based on its original value is another common operation: o X= x +11 X += 11; addition Improvements 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 input o Calculate the result o Output the result The Scanner Class y Java provides a pre-written class named Scanner, which allows you to 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:  <variable> = stdIn.nextInt();  <variable> = stdIn.nextLine(); Character Type- char y A char variable holds a single character (stored as an integer value). 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 Noto Its a compiler error! You much use escape sequences: o System.out.println(\); y Common escape sequences y

o o o o o

\ for a double quote \ for a single quote \n for newline go to first column in next line \t to move cursor to the next tab stop \\ for a backslash

y use tabs /t to do organize output String Class y String is another pre-written class from which we can make software 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 Methods o By calling methods we can do many useful things with Strings  length: returns the number of characters in the string object 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:

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 find its 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 <reference variable>.<method name> (<arguments>) Power of programming y Achieving the full power of programming requires being able to control 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 finish o Deciding (AKA: Selecting, Branching, Ch.3)  Doing something when a condition is true o Looping (AKA: Repeating, Ch. 4)  Doing something again and again as long as a condition remains true.

302 Chapter 3
if Intro y

1/26/2012 2:05:00 PM

y y

y If (year { } else {

We make decision in a program with if statements: o From if (<condition>) { o <statement(s)> o } The condition will give a true/false result And execution depends on this result o True: do the statement(s) o False: skip over them do none! Use an if statement when you wan to do one or none. >= 2012) System.out.println(This is not in the past);

System.out.println ( This year is in the past); } Comparison Pps: == != <= < >= > y one or none y Use if-else to do One or another y Use if-else-if for one of many decisions y 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); }

Good Programs y What makes a program good? y Robust y User friendly y General y Terminating y Efficient y Clear( well structured, well documented) y What makes a program general? o When it can produce the final (desired) state from many initial states General programs need to be able to decide which statements to do based on the current state of the problem. End with else only when there is 1 possibility left End with else if when there are more possibilities left that youre not considering. ELSE IF WILL NOT DO ANYTHING IF IF IS ALREADY EXECUTED

y y y y y y

Is our solution robust? 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 to work! y A more GENERAL program has fewer preconditions, but it will need to make more complicated decisions! If (month= 2) { System.out.println( February had 28 days); } else if (month =

You might also like