3.2 Creating Data Types

Similar documents
1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Java CPD (I) Frans Coenen Department of Computer Science

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Java Interview Questions and Answers

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

1.3 Conditionals and Loops

Object Oriented Software Design

CS 106 Introduction to Computer Science I

Object Oriented Software Design

Introduction to Java

Introduction to Java. CS 3: Computer Programming in Java

Contents. 9-1 Copyright (c) N. Afshartous

Java Basics: Data Types, Variables, and Loops

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Example of a Java program

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

CS170 Lab 11 Abstract Data Types & Objects

Interactive Applications (CLI) and Math

AP Computer Science Java Subset

Java Programming Fundamentals

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Sources: On the Web: Slides will be available on:

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

AP Computer Science Static Methods, Strings, User Input

Computing Concepts with Java Essentials

Arrays in Java. Working with Arrays

University of Pennsylvania. Electrical & Systems Engineering Undergraduate Laboratories. ESE 112: Introduction to Electrical & Systems Engineering

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

(Eng. Hayam Reda Seireg) Sheet Java

Part I. Multiple Choice Questions (2 points each):

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

An Overview of Java. overview-1

J a v a Quiz (Unit 3, Test 0 Practice)

LAB4 Making Classes and Objects

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CS 111 Classes I 1. Software Organization View to this point:

Maths Workshop for Parents 2. Fractions and Algebra

CPLEX Tutorial Handout

Part 3: GridWorld Classes and Interfaces

Unit 6. Loop statements

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Lecture 5: Java Fundamentals III

1.1 Your First Program

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Lesson 10: Video-Out Interface

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Computer Programming I

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Sample CSE8A midterm Multiple Choice (circle one)

public static void main(string[] args) { System.out.println("hello, world"); } }

6.1. Example: A Tip Calculator 6-1

Overview. java.math.biginteger, java.math.bigdecimal. Definition: objects are everything but primitives The eight primitive data type in Java

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Graduate Assessment Test (Sample)

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Introduction to Object-Oriented Programming

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

3D Animation of Java Program Execution for Teaching Object Oriented Concepts

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

SmartArrays and Java Frequently Asked Questions

Chapter 5. Recursion. Data Structures and Algorithms in Java

Mathematics. Mathematical Practices

Samples of Allowable Supplemental Aids for STAAR Assessments. Updates from 12/2011

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

The resulting tile cannot merge with another tile again in the same move. When a 2048 tile is created, the player wins.

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Block IQ. Marko Boon Jacques Resing

Locating and Decoding EAN-13 Barcodes from Images Captured by Digital Cameras

Chapter 19. General Matrices. An n m matrix is an array. a 11 a 12 a 1m a 21 a 22 a 2m A = a n1 a n2 a nm. The matrix A has n row vectors

Computer Programming I & II*

a 11 x 1 + a 12 x a 1n x n = b 1 a 21 x 1 + a 22 x a 2n x n = b 2.

In this Chapter you ll learn:

Chapter 13 - Inheritance

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

CS106A, Stanford Handout #38. Strings and Chars

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

TWO-DIMENSIONAL TRANSFORMATION

WRITING DATA TO A BINARY FILE

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Basics of Java Programming Input and the Scanner class

Object-Oriented Programming in Java

Object Oriented Programming Design Basics CMSC 202

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 1 October 14, Instructions

Transcription:

1

3.2 Creating Data Types

Data Types Data type. Set of values and operations on those values. Basic types. Data Type Set of Values Some Operations boolean true, false not, and, or, xor int -2 31 to 2 31-1 add, subtract, multiply String sequence of Unicode characters concatenate, compare Last time. Write programs that use data types. Today. Write programs to create our own data types. 3

Defining Data Types in Java To define a data type, we must specify: Set of values. Operations defined on them. Java class. Allows us to define data types by specifying: Instance variables. (set of values) Methods. (operations defined on them) Constructors. (create and initialize new objects) 4

Point Charge Data Type Goal. Create a data type to manipulate point charges. Set of values. Three real numbers. [position and electrical charge] Operations. Create a new point charge at (r x, r y ) with electric charge q. Determine electric potential V at (x, y) due to point charge. Convert to String. (x, y) V = k q r r = (r x x) 2 + (r y y) 2 q r = distance between (x, y) and (r x, r y ) (r x, r y ) k = electrostatic constant = 8.99 10 9 N m 2 / C 2 5

Point Charge Data Type Goal. Create a data type to manipulate point charges. Set of values. Three real numbers. [position and electrical charge] API: 6

Charge Data Type: A Simple Client Client program. Uses data type operations to calculate something. public static void main(string[] args) double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); Charge c1 = new Charge(.51,.63, 21.3); Charge c2 = new Charge(.13,.94, 81.9); double v1 = c1.potentialat(x, y); double v2 = c2.potentialat(x, y); StdOut.println(c1); StdOut.println(c2); StdOut.println(v1 + v2); automagically invokes the tostring() method % java Charge.50.50 21.3 at (0.51, 0.63) 81.9 at (0.13, 0.94) 2.74936907085912e12 7

Anatomy of Instance Variables Instance variables. Specifies the set of values. Declare outside any method. Always use access modifier private. Use modifier final with instance variables that never change. makes data type abstract makes objects immutable (stay tuned) 8

Anatomy of a Constructor Constructor. Specifies what happens when you create a new object. Invoking a constructor. Use new operator to create a new object. invoke constructor 9

Anatomy of an Instance Method Method. Define operations on instance variables. Invoking a method. Use dot operator to invoke a method in client code. object name invoke method 10

Anatomy of a Class 11

Charge Client Example: Potential Visualization Potential visualization. Read in N point charges from a file; compute total potential at each point in unit square. (And make a Picture.) % more charges.txt 9.51.63-100.50.50 40.50.72 10.33.33 5.20.20-10.70.70 10.82.72 20.85.23 30.90.12-50 % java Potential < charges.txt 12

Potential Visualization Arrays of objects. Allocate memory for the array; then allocate memory for each individual object. // Read in the data. int N = StdIn.readInt(); Charge[] a = new Charge[N]; for (int i = 0; i < N; i++) double x0 = StdIn.readDouble(); double y0 = StdIn.readDouble(); double q0 = StdIn.readDouble(); a[i] = new Charge(x0, y0, q0); 13

Potential Visualization // Plot the data. int SIZE = 512; Picture pic = new Picture(SIZE, SIZE); for (int col = 0; col < SIZE; col++) for (int row = 0; row < SIZE; row++) double V = 0.0; for (int i = 0; i < N; i++) double x = 1.0 * col / SIZE; double y = 1.0 * row / SIZE; V += a[i].potentialat(x, y); pic.show(); Color color = getcolor(v); // Arbitrary double-color map. pic.set(col, SIZE-1-row, color); (0, 0) is upper left ( ) V = k q i r i i 14

Data Type Challenge [easy if you read Exercise 3.2.5] Fix the serious bug in the following code. public class Charge private double rx, ry; private double q; public Charge (double x0, double y0, double q0) double rx = x0; double ry = y0; double q = q0; 15

Turtle Graphics

Turtle Graphics Goal. Create a data type to manipulate a turtle moving in the plane. Set of values. Location and orientation of turtle. API. // Draw a square. Turtle turtle = new Turtle(0.0, 0.0, 0.0); turtle.goforward(1.0); turtle.turnleft(90.0); turtle.goforward(1.0); turtle.turnleft(90.0); turtle.goforward(1.0); turtle.turnleft(90.0); turtle.goforward(1.0); turtle.turnleft(90.0); 18

Turtle Graphics Implementation public class Turtle private double x, y; // turtle is at (x, y) private double angle; // facing this direction public Turtle(double x0, double y0, double a0) x = x0; y = y0; angle = a0; public void turnleft(double delta) angle += delta; public void goforward(double d) double oldx = x; double oldy = y; x += d * Math.cos(Math.toRadians(angle)); y += d * Math.sin(Math.toRadians(angle)); StdDraw.line(oldx, oldy, x, y); 19

Turtle client example: N-gon public class Ngon public static void main(string[] args) int N = Integer.parseInt(args[0]); double angle = 360.0 / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < N; i++) turtle.goforward(step); turtle.turnleft(angle); 3 7 1440 20

Turtle client example: Spira Mirabilis public class Spiral public static void main(string[] args) int N = Integer.parseInt(args[0]); double decay = Double.parseDouble(args[1]); double angle = 360.0 / N; double step = Math.sin(Math.toRadians(angle/2.0)); Turtle turtle = new Turtle(0.5, 0, angle/2.0); for (int i = 0; i < 10 * N; i++) step /= decay; turtle.goforward(step); turtle.turnleft(angle); 3 1.0 3 1.2 1440 1.00004 1440 1.0004 21

Spira Mirabilis in Nature 22

Complex Numbers

Complex Number Data Type Goal. Create a data type to manipulate complex numbers. Set of values. Two real numbers: real and imaginary parts. API. a = 3 + 4i, b = -2 + 3i a + b = 1 + 7i a b = -18 + i a = 5 25

Applications of Complex Numbers Relevance. A quintessential mathematical abstraction. Applications. Fractals. Impedance in RLC circuits. Signal processing and Fourier analysis. Control theory and Laplace transforms. Quantum mechanics and Hilbert spaces.... 26

Complex Number Data Type: A Simple Client Client program. Uses data type operations to calculate something. public static void main(string[] args) Complex a = new Complex( 3.0, 4.0); Complex b = new Complex(-2.0, 3.0); Complex c = a.times(b); StdOut.println("a = " + a); StdOut.println("b = " + b); StdOut.println("c = " + c); % java TestClient a = 3.0 + 4.0i result of c.tostring() b = -2.0 + 3.0i c = -18.0 + 1.0i Remark. Can't write a = b*c since no operator overloading in Java. 27

Complex Number Data Type: Implementation public class Complex private final double re; private final double im; public Complex(double real, double imag) re = real; im = imag; public String tostring() return re + " + " + im + "i"; public double abs() return Math.sqrt(re*re + im*im); public Complex plus(complex b) double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); public Complex times(complex b) double real = re * b.re im * b.im; double imag = re * b.im + im * b.re; return new Complex(real, imag); instance variables constructor methods refers to b's instance variables 28

Mandelbrot Set Mandelbrot set. A particular set of complex numbers. Plot. Plot (x, y) black if z = x + y i is in the set, and white otherwise. Benoit Mandelbrot 1924-2010 No simple formula describes which complex numbers are in set. Instead, describe using an algorithm. 29

Mandelbrot Set Mandelbrot set. Is complex number z 0 in set? Iterate z t + 1 = (z t ) 2 + z 0. If z t diverges to infinity, then z 0 not in set; otherwise z 0 is in set. t z t t z t 0-1/2 + 0i 0 1 + i 1-1/4 + 0i 1 1 + 3i 2-7/16 + 0i 2-7 + 7i 3-79/256 + 0i 3 1-97i 4-26527/65536 + 0i 4-9407 193i 5-1443801919/4294967296 + 0i 5 88454401 + 3631103i z = -1/2 + 0i is in Mandelbrot set z = 1 + i is not in Mandelbrot set 30

Plotting the Mandelbrot Set Practical issues. Cannot plot infinitely many points. Cannot iterate infinitely many times. Approximate solution. Sample from an N-by-N grid of points in the plane. Fact: if z t > 2 for any t, then z not in Mandelbrot set. Pseudo-fact: if z 255 2 then z "likely" in Mandelbrot set. (0.5, 1) -0.5 + 0i (-1.5, -1) 8-by-8 grid 31

Complex Number Data Type: Another Client Mandelbrot function with complex numbers. Is z in the Mandelbrot set? Returns white (definitely no) or black (probably yes). public static Color mand(complex z0) Complex z = z0; for (int t = 0; t < 255; t++) if (z.abs() > 2.0) return Color.WHITE; z = z.times(z); z = z.plus(z0); z = z 2 + z 0 return Color.BLACK; More dramatic picture: replace Color.WHITE with grayscale or color. new Color(255-t, 255-t, 255-t) 32

Complex Number Data Type: Another Client Plot the Mandelbrot set in gray scale. public static void main(string[] args) double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); int N = 512; Picture pic = new Picture(N, N); for (int x = 0; x < N; x++) for (int y = 0; y < N; y++) double x0 = xc - size/2 + size*x/n; double y0 = yc - size/2 + size*y/n; Complex z0 = new Complex(x0, y0); Color color = mand(z0); pic.set(x, N-1-y, color); (0, 0) is upper left pic.show(); scale to screen coordinates 33

Mandelbrot Set % java Mandelbrot.5 0 2 % java Mandelbrot.1045 -.637.01 34

Mandelbrot Set % java ColorMandelbrot 1.5 0 2 < mandel.txt 1.5 0.02 1.5 0.002 35

36

Mandelbrot Set (-1.5, -1) 37