lecture 8: bits and pieces tami meredith. roadmap today's lecture has a bit of everything. going...

35
CSCI1226 Introduction to Computing Science and Programming Lecture 8: Bits and Pieces Tami Meredith

Upload: tracy-andrews

Post on 20-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Slide 1

CSCI1226Introduction to Computing Science and Programming Lecture 8: Bits and Pieces Tami MeredithRoadmapToday's lecture has a bit of everything.Going back over previous chapters and pulling out little bits I haven't covered yet or did not cover in much depthProviding gentle introductions to things you don't really need to know, but that you should be aware that they existLots and lots of exercises MethodsBuildings are too big to be designed in a single drawingArchitects design houses in parts a basement floor plan, a first floor plan, an exterior (lot) plan, and so on ...Programs are also too big to be designed as a single partWe break programs into parts these parts are called methodsA method is PART of a program it will not execute/run by itselfMethods need data to work:Input from other parts of the program, via parametersOutput to other parts of the program, via the return value

A Methodpublic static boolean isEven (int val) { if ((val % 2) == 0) { return (true); } else { return (false);}Input: val, of type intOutput (return value): a booleanThis method is only part of a program, it won't work by itselfA named block of code, the block is called isEven

ExerciseWrite a method that takes two strings and returns (as a new string) the longest common prefix of both stringsE.g., the longest prefix of "Money" and "Motion" is "Mo"The method should be case sensitiveSolution// Note: Fails if si is a prefix of sjpublic static String lcp (String s1, String s2){ int i = 0; while (s1.charAt(i) == s2.charAt(i)) { i++; } return (s1.substring(0,i));}

Variable ModificationWe can modify variables in several ways:Assignment: x = 7; y = 3 * x;Increment/Decrement: x++; --y;Combined assignment and an operation: x += 1; This is called compound assignment.The compound operators are: +=, -=, *=, /=, %= (there are more, &=, y) ? x : y;mean = (n == 0) ? 0 : sum/n;

Syntactic SugarThe statement mean = (n == 0) ? 0 : sum/n;Is really just a compact way of sayingif (n == 0) mean = 0;else mean = sum/n;The term syntactic sugar is used to refer to optional (not really needed) constructs that make code "sweeter" to readCompound assignment is another example of syntactic sugar, e.g., x += 7; is the same as x = x + 7;

PrecedenceThere is a complex precedence (order of operations) for Java's operatorsDON'T rely on it, DON'T waste a lot of effort memorising itINSTEAD use parentheses (i.e., '(' and ')') liberally to make things happen in the order that you wantParentheses also make things much clearer as well as avoiding surprise/errors due to precedenceSee: TextFig 3.9

ShiftsIt is possible to work with the individual bits of a valueThis is an advanced technique that is used to create more efficient code (save time or space)We will not be doing any shifts, but you should know that they existbyte x = 9; // x = 0000 1001; x = x > 1; // x = 0001 0010;Bitwise OperationsLike shifts, bitwise operations work on the specific bits of a valueThey are another advanced tool that you won't need in this course, but are useful to be aware ofNOTE: & is not the same as &&, will generate different results| is not the same as ||, will generate different results^ is an operatorKnowing they are here and different will help you find and hopefully avoid mistakesKeyboard Input (Review)It is useful to get input from the userUntil now we have provided the code to do this for youSystem.in is an object of type InputStreamIt is not very useful since you can only read bytes from an InputStreamWe apply a Scanner to the InputStream to Break the stream into meaningful parts (e.g., integers, lines, words)Change the parts into useful types (e.g., ints, floats, Strings)Useful MethodsSee Figure 2.7 (Page 98) of the textnext(), gets the next wordnextLine(), gets the next line, discards the newlinenextInt(), gets the next integerhasNextLine(), checks if there is another line, returns a booleanhasNextInt(), checks if there is another int, returns a booleanThere are many other methods you can use, see:http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

You need to know the delimiter what ends a word, an integer, etc.Example (Code Fragments) import java.util.Scanner;// import java.util.*;

Scanner scn= new Scanner(System.in);String line;

if (scn.hasNextLine()) { line = scn.nextline();} ExerciseWrite a program that asks the user for a pair of integers and prints all the even numbers (in increasing order) between the two integersThe output should be on one line and separated by commasExample:Enter the first number: 11Enter the second number: 44, 6, 8, 10Solutionimport java.util.Scanner;public class evens { public static void main (String[] args) { Scanner keyboard = new Scanner (System.in); System.out.print("Enter the first integer: "); int i1 = keyboard.nextInt(); System.out.print("Enter the second integer: "); int i2 = keyboard.nextInt();

int start = (i1 < i2) ? i1 : i2; start = ((start % 2) == 0) ? start : start + 1; int end = (i2 > i1) ? i2 : i1; end = ((end % 2) == 0) ? end : end 1;

for (int i = start; i 0) || (s = "Empty")) { System.out.println("String is: " + s);}ASCIIEvery 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)

HexidecimalOur ASCII table had "hex" valuesHexidecimal is base 16Digits are 0, 1, ... , 0, A, B, C, D, E, F (lower case is OK)Hex is used a lot by programmers because 16 is a power of 2 and can be represented by 4 bitsAgain, you don't need to know it, but being aware that it exists is usefulPrefix hex constants with 0xint x = 0x10; // x = hexidecimal 10 = 16;ExerciseWrite a program that prints out the letters of the alphabet in the following format:A, aB, bC, c...Z, zNote, you don't need hexidecimal for this (or any) exercise, I mentioned it so you'd know what Hex meant in the ASCII tableSolutionpublic class alphabet { public static void main (String[] args) { char lower = 'a', upper = 'A'; do { System.out.println( upper++ + ", " + lower++); } while (upper