CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009

Embed Size (px)

DESCRIPTION

Today Increment/decrement operators Escape sequences in string output. Strings More on using pre-defined methods. Reference objects

Text of CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009

  • CSCI 51Introduction to Computer ScienceJoshua StoughFebruary 3, 2009

  • AnnouncementsTutoring Schedule onlineSunday 8-10PM (Spiller)Monday 4-6PM (Stough), 8-10PM (Siegel)Tuesday 8-10PM (Siegel)Wednesday 4-6PM (Stough)Thursday 4-6PM (Spiller)Friday 3-5PM (Stough)

    Card Access one more step See Kace Kush in Story House for card activation for Adams Hall after-hours access

  • TodayIncrement/decrement operatorsEscape sequences in string output.StringsMore on using pre-defined methods.Reference objects

  • More OperatorsIncrement and DecrementIncrement (++)adds 1 to any integer or floating point

    count++;count = count + 1;

    Decrement (--)subtracts 1 from any integer or floating point

    count--;count = count - 1;

  • Increment and DecrementPrefix(++count or --count)value used in a larger expression is the new value of count (after the increment/decrement)

    Postfix(count++ or count--)value used in a larger expression is the original value of count (before the increment/decrement)increment/decrement is the last operation performed (even after assignment)

  • Increment and DecrementIf count currently contains 45, then the statement

    total = count++;assigns 45 to total and then 46 to countIf count currently contains 45, then the statement

    total = ++count;assigns the value 46 to both total and count

  • QuestionsWhat is stored in total and count in the following statements?

    double total = 15.5;total++;

    int total = 10, count = 5;total = total + count++;

    int total = 20, count = 3;total = total / --count;total 16.5total count15 6total count10 2

    total = 16.5 total = 15, count = 6 total = 10, count = 2

  • Escape Sequences in outputEscape character \Used to represent special characters inside StringsEscape sequences\n - newline\t - tab\b - backspace\r - return\\ - backslash\' - single quote\" - double quote

  • Examples

    System.out.println ("I said, \"Hi There!\"");I said, "Hi There!"System.out.print ("Hello\n");System.out.println ("World");HelloWorldSystem.out.println ("Hello\rWorld");HelloWorldSystem.out.println ("Hi\b\bHello");HelloSystem.out.println ("Hello\tWorld");HelloWorld

  • QuestionsWhat is output by the following statements?System.out.println ("Helen says " + "\"What\'s up?\"");

    System.out.print ("Enter a number ");System.out.println ("between 1-10");System.out.print ("\n\tplease!");Helen says "What's up?"Enter a number between 1-10

    please!

  • The class StringString variables are reference variablesGiven String name; Equivalent Statements:

    name = new String("Lisa Simpson");name = "Lisa Simpson";

  • name = "Lisa Simpson";

    Lisa SimpsonLisa SimpsonLisa Simpson

  • The class StringThe String object is an instance of class stringThe value Lisa Simpson is instantiatedThe address of the value is stored in nameThe new operator is unnecessary when instantiating Java stringsString methods are called using the dot operator

  • Common String MethodsString(String str)constructorcreates and initializes the objectchar charAt(int index)returns char at the position specified by index (starts at 0)int indexOf(char ch)returns the index of the first occurrence of chint compareTo(String str)returns negative if this string is less than strreturns 0 if this string is the same as strreturns positive if this string is greater than str

    All String class methods are in Appendix E (pgs. 914-916)

  • Common String Methodsboolean equals(String str)returns true if this string equals strint length()returns the length of the stringString replace(char toBeReplaced, char replacedWith)returns the string in which every occurrence of toBeReplaced is replaced with replacedWithString toLowerCase()returns the string that is the the same as this string, but all lower caseString toUpperCase()returns the string that is the same as this string, but all upper case

  • String ExamplesString str = "Go Trojans!";

    System.out.println (str.length());

    System.out.println (str.charAt(3));

    System.out.println (str.indexOf('!');

    System.out.println (str.toLowerCase());T1211go trojans!

    The value in str does not change unless you assign something to it. Using the methods here, doesn't change the value of the string.

  • Glossary TermsClass - used to group a set of related operations (methods), allows users to create their own data types Method - set of instructions designed to accomplish a specific task Package - collection of related classesLibrary - collection of packages

  • PackagesThe classes of Java library are organized into packages.Some of the packages in the standard class library are:

    Well talk about how to use these next...

  • Using PackagesWe need to import some of the packages we want to usejava.util for Scannernot java.lang because it's automatically imported for us

    import packageName;import java.util.*;imports all of the classes in the java.io packageimport java.util.Scanner;imports only the Scanner class from the java.util package

  • Using Predefined Classes and Methodslong Math::round (double);To use a method you must know:Name of class containing method (Math)Name of package containing class (java.lang)Name of method (round), its parameters (double a), what it returns (long), and function (rounds a to the nearest integer)

  • Using Predefined Classes and MethodsExample method call:

    int num = (int) Math.round (4.6);

    why don't we have to import the Math class?

    (Dot) . Operator: used to access the method in the class

    Heads up -- you'll need to use Math.round in Program 1

  • Java Program Skeletonimport statements if any

    public class ClassName{declare named constants and/or stream objects

    public static void main (String[] args) throws IOException{variable declarationsexecutable statements}}

  • Import StatementsTell the compiler which packages are used in the programImport statements and program statements constitute the source code

    Source code saved in a file with the extension .javaSource code file must have the same name as the class with the main method

  • The main methodHeading

    Bodystatements enclosed by { }declaration statementsused to declare things such as variablesexecutable statementsperform calculations, manipulate data, create output, accept input, etc.

    public static void main (String[] args)

  • staticHeading of the main method has the reserved word static

    Statements to declare named constants and input stream objects are outside the main method

    These must also be declared with the static reserved word

    Later on in the semester, we'll talk more about the static keyword

  • SyntaxSyntaxbeware! a syntax error in one place might lead to syntax errors in several other places

    Use of semicolons, braces, commasall Java statements end with semicolonbraces {} enclose the body of a method and cut it off from other parts of the program (also have other uses)commas separate list items

  • StyleSemanticsset of rules that gives meaning to a languagebeware! the compiler will not be able to tell you about semantic errors (example: missing parentheses in mathematical expression)

    Documentationcomments - shown in green in Eclipsenaming rulesuse meaningful identifiersprompt lineslet the user know what type of input is expected

  • Style and White SpaceWhite spaceblanks, tabs, blank linesused to separate words and symbolsextra space is ignored by computerblank line between variable declaration and rest of code

    Programs should be formatted to enhance readability, using consistent indentation

    Read over the "General Coding Style Guidelines" under the Completing Assignments heading in Course Documents on the course Blackboard site.

  • CommentsNot used by the computeronly for human consumption

    Used to help others understand codeexplain and show steps in algorithmcomments are essential!

    Should be well-written and clear

    Comment while coding

    Also called inline documentation

  • /**************************************************************** * Program 0: Hello World * * Programmer: Joshua Stough * * Due Date: September 2, 2008 * * Class: COMP 14 Instructor: Dr. Joshua Stough * * * Description: This program prints out a greeting to the world. * * Input: None * * Output: A friendly greeting ***************************************************************/

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

  • ReviewIn the Java programming language:a program is made up of one or more classesa class contains one or more methodsa method contains program statementsA Java application always contains a method called mainSource code saved in a file with the extension .javaFile must have the same name as the class with the main methodUse the dot (.) operator to call methods:

    Math.round

  • Review-Skeletonimport statements if any

    public class ClassName{declare named constants and/or stream objects

    public static void main (String[] args) throws IOException{variable declarationsexecutable statements}}

  • Review QuestionsWhat is stored in num?int num = (int) Math.round (12.7);

    What is printed to the screen? Assume the user enters 10 and that scan is already defined.System.out.print ("Enter a number: ");int num = scan.nextInt();System.out.println (num * num);13Enter a number: 10100

  • QuestionsWhat is stored in total and count in the following statements?

    int total = 10, count = 5;total += count++;

    int total = 20, count