54
CSCI1227 Computer Programming and Problem Solving Lecture 2: 1226 Review Tami Meredith

Lecture 2: 1226 Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User

Embed Size (px)

Citation preview

Slide 1

CSCI1227Computer Programming andProblem Solving Lecture 2: 1226 Review Tami MeredithProgramming ProcessHow do we fill in the yellow box?TextEditorCompiler(javac)Interpreter (JVM: java)UserLibrariesOperating System (Windows)OutputInputJDKProgramming RequiresIdentification of the problemUnderstanding it, identifying correct solutionsSolving the problem:Selecting the data structures, andData Management is the key hereIdentifying an algorithmControl Flow is the basis of algorithmsCoding the solutionTesting, debugging, verifying the solutionWhat is a Program?Programs = Data + AlgorithmsData: the nouns, the things we manipulateAlgorithms: the verbs, the actions we performA program manipulates the input (data) to produce the required output (data)Some Common Data TypesCharacters: Things from the keyboard'a', 'b', 'Z', '!', '\n'Strings: Sequences of characters"hi there", "Hello, Bob!", "x", "RESULT"Integers: Whole numbers, byte, short, int, long-3097, -2, -1, 0, 1, 10, 10340Floating Point Numbers: float, double (have decimals)1.0, 3.14, .333, 100000.0000001Booleans: Truth values for teststrue, falseNothing: The empty type with no valuevoidASCIIEvery character has a valueWe store the value, not the characterWe can treat characters as numbers as a consequenceThe values assigned are based on the ASCII encoding0-127: Basic ASCII128-255: Extended ASCII256-65535: Unicode (subsumes ASCII)

Escaped CharactersSometimes we want to remove or add meaning to characters in a string (Figure 2.6)Can also use this notation to represent characters from the ASCII tableTo do this we use the escape character '\' to escape the normal meaning of the next character\" double quote, don't end the string\' single quote\\ - just a backslash, not an escape\n newline (go to beginning of next line)\t tab, expanded using system default\r carriage return (same as newline ... maybe)IntegersThere are four kinds of integersThe main difference is the minimum and maximum valuesbyte: -128 to 127short: -32 768 to 32 767int: -2 147 483 648 to 2 147 483 647long: -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807Difference is caused by the amount of memory used to store each onebyte = 1 byte, short = 2 bytes int = 4 bytes long = 8 bytesVariablesint i;Defines a section of memory large enough to hold an integer and names that area of memory "i", the memory contains a random value from whatever it was used for previouslyi = 5;Stores the value 5 in the area or memory named "i"int i = 5; Combines 1. and 2.A variable holds one, and only one, thingA variable always has a value ... if you put nothing there then assume it has a random value

VariablesVariables describe memory locationsValues are stored in those locationsIdentifiers name locations

int x = 13; location x 13

Right Hand Side (of =): Use the value stored in the location (used also when no = in expression)Left Hand Side (of =): Use the location to store the valueOperatorsStandard math: +, -, *, /Modulus (Remainder): %Assignment to a variable name uses =Can change the type of something using a castint x = 1;float y = (float) x;+ is also string concatenatione.g., "Hi " + "there" creates "Hi there"

See: TextFig 3.9

Delimiters" "A string (sequence of zero or more characters)'a'A character (a single character, never empty){ }A block (sequence of zero or more statements)/* */A multi-line comment[ ]An array index( )A math expressionA test in a loop or conditionalThe arguments of a method callThe parameters in a method declarationprintfAn alternative to print or printlnVery powerful and flexiblee.g., System.out.printf("An integer: %d", i);Format: System.out.printf(format-string, values...);The format-string is printed and every specifier (things that begin with a %) is replaced with one of the valuesThere must be the same number of values as specifiersIt was originally in the C programming language and was added to Java because a lot of C programmers wanted it! Described on page 101 102

Format Specifiers%c a character%s a string%d an integer%f a floating point numberWe can modify the values to have a minimum and a maximum size, left or right justify numbers, pad with leading/trailing zeros, create columns, etc.E.g., %5d an integer with 5 digits (spaces added if needed)See: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntaxprintfprintf (format-string, ... values ...)There must be one value for every specifier in the format stringformat specifiers begin with a % and are placed in the format stringE.g. printf("Hello %s!", name);In this example %s means, put a string here, and name is used to provide the stringSame as print("Hello " + name + "!");There might not be any values!E.g., printf("Hello!"); is the same as print("Hello!");

ExamplesSystem.out.printf ("%d * %d = %d\n", 3, 4, 3*4);System.out.println(3 + " * " + 4 + " = " + (3*4));System.out.print (3 + " * " + 4 + " = " + (3*4) + "\n");

3 * 4 = 12

System.out.printf ("%s\n%s\n", "Tami", "Meredith");System.out.println("Tami\nMeredith");System.out.print ("Tami\nMeredith\n");

Tami Meredith

StringsStrings are a special data type (Strings are actually objects)Ordered and numbered sequences of charactersIndexed from 0Delimited by double quotesE.g., "Hello World!", "", "tami"Large library of String manipulation methods existsString MethodsSee Figure 2.5 in the text (page 86)replace(c1,c2) and replace(ss1,ss2) replace all occurances of c1/ss1 with c2/ss2length() returns the length of a string (as an integer)indexOf(string2) returns the index of string2 in string or -1 if string2 is contained in stringequals(string2) returns TRUE if string equals string2 otherwise it returns FALSEString sentence = "Hello programming class";int len = sentence.length();boolean same = sentence.equals("Good bye!");

ExerciseWrite a program that has a single String variable containing your name as 2 or more wordse.g., String name = "Tami Michelle Meredith";The program will tell you how many words your name had. The program must still work correctly if someone changes the name to have a different number of words.e.g., Tami Michelle Meredith has 3 names.

Solutionpublic class howMany {

public static void main (String[] args) {

String name = "Tami Michelle Meredith"; String spaceless = name.replace(" ", ""); int num = name.length() spaceless.length() + 1;

System.out.println(name + " has " + num + " names.");

} // end main()

} // end class howManyControl is Power!Control flow is actually very simple:Everything is sequential, unless ...Something is optionalConditional Statements, i.e,. ifSomething is repeatedLooping Statements, i.e., do, for, whileSomething complex is broken into simpler partsMethods (and classes, objects)Programs in JavaPrograms are structured hierarchically:Programs have 1 or more classesFiles are named after the classes they containClasses contain 1 or more methodsThe class that is used to start execution must contain a method named mainMethods perform 1 or more actionsActions are performed by statements

About Statements ...Statements are like sentences in a programming languageStatements usually end with a ";" (semi-colon)Statements are performed sequentially, one after the other (generally left to right, top to bottom)For example: x = x + 1;y = 2 * x;System.out.println("Y is " + y); StatementsExpressions and assignmentse.g., x = 3 * y;Conditional statements to make choicese.g., if (x == 0) System.exit(0);Loops to repeat thingse.g., while (i > 0) System.out.println(i--);Blocks to group statements into a single statemente.g., { statement1; statement2; statement3; ... }BlocksStatements can be grouped into a blockA block is treated like a single statement and can be used where a single statement is expectedBlocks are formed by surrounding a group of statements with curly braces, "{" and "}"For example: { y = x * 2; System.out.print("Two times " + x + " is " + y);}

Conditional StatementsConditionals make a choice of whether a statement should be executed:Syntax: if (test) statementWhen test evaluates to true, statement is executedstatement is singular, a block must be used to do more than one thing when test is trueAlternate Syntax:if (test) statement1 else statement2If test is equal to true then do statement1If test is equal to false then do statement2Note that there is no ";" at the end of the conditionalConditional Expressionsif (sex == 'f') System.out.printf("female");else System.out.printf("male");

>

System.out.printf("%smale", (sex=='f') ? "fe" : "");

Format:(test) ? use-if-true : use-if-false

LoopsExecutes a statement more than onceSyntax:while (test) statementEvaluate testIf test is equal to true, do step 3, otherwise donePerform statement then go back to 1Note that statement is singular and that the loop does not end with a ";" (but statement does)

Example // Code fragment, counts from 0 to // the value "stop" input by the user

int count = 0;int stop = user.nextInt();

while (count