Question? Leave a message!




Using Data Types

Using Data Types
3.1 Using Data Types Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 3/18/11 9:05 AM A Foundation for Programming any program you might want to write create your own objects data types functions and modules graphics, sound, and image I/O arrays conditionals and loops Math text I/O primitive data types assignment statements 2 Data Types Data type. Set of values and operations on those values. Primitive types. Ops directly translate to machine instructions. Data Type Set of Values Operations boolean true, false not, and, or, xor 31 31 int 2 to 2 1 add, subtract, multiply 64 double any of 2 possible reals add, subtract, multiply We want to write programs that process other types of data.   Colors, pictures, strings, input streams, …   Complex numbers, vectors, matrices, polynomials, …   Points, polygons, charged particles, celestial bodies, … 3 Objects Object. Holds a data type value; variable name refers to object. Impact. Enables us to create our own data types; define operations on them; and integrate into our programs. Data Type Set of Values Operations Color 24 bits get red component, brighten Picture 2D array of colors get/set color of pixel (i, j) String sequence of characters length, substring, compare 4 Constructors and Methods To construct a new object: Use keyword new and name of data type. To apply an operation: Use name of object, the dot operator, and the name of the method. 5 Image Processing Color Data Type Color. A sensation in the eye from electromagnetic radiation. 3 Set of values. RGB representation 256 possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to 255. R G B Color 255 0 0 0 255 0 0 0 255 255 255 255 0 0 0 255 0 255 105 105 105 7 Color Data Type Color. A sensation in the eye from electromagnetic radiation. 3 Set of values. RGB representation 256 possible values, which quantify the amount of red, green, and blue, each on a scale of 0 to 255. API. Application Programming Interface. http://download.oracle.com/javase/6/docs/api/java/awt/Color.html 8 Albers Squares Josef Albers. Revolutionized the way people think about color. Homage to the Square by Josef Albers (19491975) 9 Albers Squares Josef Albers. Revolutionized the way people think about color. gray blue java AlbersSquares 9 90 166 100 100 100 10 Using Colors in Java to access Color library import java.awt.Color; public class AlbersSquares public static void main(String args) int r1 = Integer.parseInt(args0); int g1 = Integer.parseInt(args1); first color int b1 = Integer.parseInt(args2); Color c1 = new Color(r1, g1, b1); int r2 = Integer.parseInt(args3); int g2 = Integer.parseInt(args4); second color int b2 = Integer.parseInt(args5); Color c2 = new Color(r2, g2, b2); StdDraw.setPenColor(c1); first square StdDraw.filledSquare(.25, .5, .2); StdDraw.setPenColor(c2); StdDraw.filledSquare(.25, .5, .1); StdDraw.setPenColor(c2); StdDraw.filledSquare(.75, .5, .2); second square StdDraw.setPenColor(c1); StdDraw.filledSquare(.75, .5, .1); 11 Monochrome Luminance Monochrome luminance. Effective brightness of a color. NTSC formula. Y = 0.299r + 0.587g + 0.114b. import java.awt.Color; public class Luminance public static double lum(Color c) int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); return .299r + .587g + .114b; 12 Color Compatibility Q. Which font colors will be most readable with which background colors on computer and cell phone screens A. Rule of thumb: difference in luminance should be 128. 256 208 105 47 28 14 public static boolean compatible(Color a, Color b) return Math.abs(lum(a) lum(b)) = 128.0; 13 Grayscale Grayscale. When all three R, G, and B values are the same, resulting color is on grayscale from 0 (black) to 255 (white). Convert to grayscale. Use luminance to determine value. public static Color toGray(Color c) int y = (int) Math.round(lum(c)); Color gray = new Color(y, y, y); return gray; round double to nearest int Bottom line. We are writing programs that manipulate color. 14 OOP Context for Color Possible memory representation. D0 D1 D2 D3 D4 D5 D6 D7 D8 255 0 255 0 0 0 105 105 105 A0 B0 gray magenta D0 D6 memory address ("pointer") Object reference is analogous to variable name.   We can manipulate the value that it holds.   We can pass it to (or return it from) a method. 15 References René Magritte. "This is not a pipe." Java. This is not a color. Color sienna = new Color(160, 82, 45); Color c = sienna.darker(); OOP. Natural vehicle for studying abstract models of the real world. 16 Picture Data Type Raster graphics. Basis for image processing. Set of values. 2D array of Color objects (pixels). API. 18 Image Processing: Grayscale Filter Goal. Convert color image to grayscale according to luminance formula. import java.awt.Color; public class Grayscale public static void main(String args) Picture pic = new Picture(args0); for (int x = 0; x pic.width(); x++) for (int y = 0; y pic.height(); y++) Color color = pic.get(x, y); from before Color gray = Luminance.toGray(color); pic.set(x, y, gray); pic.show(); 19 Image Processing: Grayscale Filter Goal. Convert color image to grayscale according to luminance formula. mandrill.jpg java Grayscale mandrill.jpg 20 Image Processing: Scaling Filter Goal. Shrink or enlarge an image to desired size. Downscaling. To shrink, delete half the rows and columns. Upscaling. To enlarge, replace each pixel by 4 copies. 21 Image Processing: Scaling Filter Goal. Shrink or enlarge an image to desired size. Uniform strategy. To convert from w byh to w byh : s s t t   Scale column index by w / w . s t   Scale row index by h / h . s t   Set color of pixel (x, y) in target image to color of pixel (x " w / w , y " h / h ) in source image. s t s t x " w / w s t x y y " h / h s t source image target image (w byh ) (w byh ) s s t t 22 Image Processing: Scaling Filter import java.awt.Color; public class Scale public static void main(String args) String filename = args0; int w = Integer.parseInt(args1); int h = Integer.parseInt(args2); Picture source = new Picture(filename); Picture target = new Picture(w, h); for (int tx = 0; tx target.width(); tx++) for (int ty = 0; ty target.height(); ty++) int sx = tx source.width() / target.width(); int sy = ty source.height() / target.height(); Color color = source.get(sx, sy); target.set(tx, ty, color); source.show(); target.show(); 23 Image Processing: Scaling Filter Scaling filter. Creates two Picture objects and two windows. java Scale mandrill.jpg 400 200 mandrill.jpg (298by298) 24 More Image Processing Effects RGB color separation swirl filter wave filter glass filter Sobel edge detection 25 Text Processing String Data Type String data type. Basis for text processing. Set of values. Sequence of Unicode characters. API. … http://download.oracle.com/javase/6/docs/api/java/lang/String.html 27 Typical String Processing Code 28 Gene Finding Pregenomics era. Sequence a human genome. Postgenomics era. Analyze the data and understand structure. Genomics. Represent genome as a string over A, C, T, G alphabet. Gene. A substring of genome that represents a functional unit.   Preceded by ATG. start codon   Multiple of 3 nucleotides. codons other than start/stop   Succeeded by TAG, TAA, or TGA. stop codons Goal. Find all genes. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 A T A G A T G C A T A G C G C A T A G C T A G A T G T G C T A G C start gene stop gene 29 Gene Finding: Algorithm Algorithm. Scan lefttoright through genome.   If start codon, then set beg to index i.   If stop codon and substring is a multiple of 3 –  output gene –  reset beg to 1 multiple of 3 30 Gene Finding: Implementation public class GeneFind public static void main(String args) String start = args0; String stop = args1; String genome = StdIn.readAll(); int beg = 1; for (int i = 0; i genome.length() 2; i++) String codon = genome.substring(i, i+3); if (codon.equals(start)) beg = i; if (codon.equals(stop) beg = 1) String gene = genome.substring(beg+3, i); if (gene.length() 3 == 0) StdOut.println(gene); beg = 1; more genomeTiny.txt ATAGATGCATAGCGCATAGCTAGATGTGCTAGC java GeneFind ATG TAG genomeTiny.txt CATAGCGCA TGC 31 OOP Context for Strings Possible memory representation of a string.   genome = "aacaagtttacaagc"; genome D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE A0 A1 a a c a a g t t t a c a a g c D0 15 memory length s t address B2 B3 B0 B1   s = genome.substring(1, 5); D9 4 D1 4   t = genome.substring(9, 13); s and t are different strings that share the same value "acaa"   (s == t) is false, but (s.equals(t)) is true. compares pointers compares character sequences 33 In and Out Bird's Eye View (Revisited) 35 NonStandard Input or use OS to redirect from one file Standard input. Read from terminal window. Goal. Read from several different input streams. In data type. Read text from stdin, a file, a web site, or network. Ex: Are two text files identical public class Diff public static void main(String args) In in0 = new In(args0); read from one file In in1 = new In(args1); read from another file String s = in0.readAll(); String t = in1.readAll(); StdOut.println(s.equals(t)); 36 Screen Scraping Goal. Find current stock price of Google. … tr td class="yfnctablehead1" width="48" Last Trade: /td td class="yfnctabledata1" big b459.52/b /big /td /tr tr td class="yfnctablehead1" width="48" Trade Time: /td td class="yfnctabledata1" 11:45AM ET /td /tr … http://finance.yahoo.com/qs=goog NYSE symbol 37 Screen Scraping Goal. Find current stock price of Google.   s.indexOf(t, i): index of first occurrence of pattern t in string s, starting at offset i.   Read raw html from http://finance.yahoo.com/qs=goog.   Find first string delimited by b and /b after Last Trade. public class StockQuote public static void main(String args) String name = "http://finance.yahoo.com/qs="; In in = new In(name + args0); String input = in.readAll(); int start = input.indexOf("Last Trade:", 0); int from = input.indexOf("b", start); int to = input.indexOf("/b", from); String price = input.substring(from + 3, to); StdOut.println(price); java StockQuote goog 616.50 38 Day Trader Add bells and whistles.   Plot price in realtime.   Notify user if price dips below a certain price.   Embed logic to determine when to buy and sell.   Automatically send buy and sell orders to trading firm. Warning. Please, please use at your own financial risk. The New Yorker, September 6, 1999 39 OOP Summary Object. Holds a data type value; variable name refers to object. In Java, programs manipulate references to objects.   Exception: primitive types, e.g., boolean, int, double.   Reference types: String, Picture, Color, arrays, everything else.   OOP purist: language should not have separate primitive types. Bottom line. We wrote programs that manipulate colors, pictures, and strings. Next time. We'll write programs that manipulate our own abstractions. 40
Website URL
Comment