Week 3: Objects, Input and Processing

Similar documents
Week 2: Data and Output

CS 170 Java Programming 1. Week 5: Procedures and Functions

CS 170 Java Programming 1. Week 9: Learning about Loops

CS 170 Java Programming 1. Week 12: Creating Your Own Types

CS 170 Java Programming 1. Week 10: Loops and Arrays

CS 170 Java Programming 1. Week 13: Classes, Testing, Debugging

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

CS 170 Java Programming 1. Week 7: More on Logic

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Structured Programming

Full file at

Express Yourself. The Great Divide

We will work with Turtles in a World in Java. Seymour Papert at MIT in the 60s. We have to define what we mean by a Turtle to the computer

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

CEN 414 Java Programming

Arithmetic and IO. 25 August 2017

Express Yourself. What is Eclipse?

Creating objects TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Full file at

Express Yourself. Writing Your Own Classes

Outline. Turtles. Creating objects. Turtles. Turtles in Java 1/27/2011 TOPIC 3 INTRODUCTION TO PROGRAMMING. Making things to program with.

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

Watkins Mill High School. Algebra 2. Math Challenge

Introduction to Java Applications

Values, Variables, Types & Arithmetic Expressions. Agenda

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Welcome to the Primitives and Expressions Lab!

Slide 1 CS 170 Java Programming 1 Real Numbers Duration: 00:00:54 Advance mode: Auto

I. Variables and Data Type week 3

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

COMP 202 Java in one week

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

1-6 Order of Operations

CS111: PROGRAMMING LANGUAGE II

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

What did we talk about last time? Examples switch statements

Slide 1 CS 170 Java Programming 1

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

CS 302: Introduction to Programming

Midterms Save the Dates!

Fundamentals of Programming Data Types & Methods

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

CS102: Variables and Expressions

Lecture 1. Course Overview Types & Expressions

Decisions, Decisions. Testing, testing C H A P T E R 7

Spring CS Homework 3 p. 1. CS Homework 3

Com S 127 Lab 2. For the first two parts of the lab, start up Wing 101 and use the Python shell window to try everything out.

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Topic 4 Expressions and variables

Ex: If you use a program to record sales, you will want to remember data:

Chapter 2. Elementary Programming

Expressions and Casting

Slide 1 CS 170 Java Programming 1 Testing Karel

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Introduction to Programming in Turing. Input, Output, and Variables

by Pearson Education, Inc. All Rights Reserved. 2

Unit 3. Operators. School of Science and Technology INTRODUCTION

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

What we will do today Explain and look at examples of. Programs that examine data. Data types. Topic 4. variables. expressions. assignment statements

Lecture 3 Tao Wang 1

Methods CSC 121 Spring 2017 Howard Rosenthal

CS 102 Lab 3 Fall 2012

Fundamentals: Expressions and Assignment

CS 150 Lab 3 Arithmetic and the Debugger. Lab 3.0 We are going to begin using the Visual Studio 2017 debugger to aid with debugging programs.

Outline. Review of Last Week II. Review of Last Week. Computer Memory. Review Variables and Memory. February 7, Data Types

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

LAB: INTRODUCTION TO FUNCTIONS IN C++

St. Edmund Preparatory High School Brooklyn, NY

Control Statements: Part 1

Condition Controlled Loops. Introduction to Programming - Python

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

Methods CSC 121 Fall 2016 Howard Rosenthal

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Basic Programming Elements

First Java Program - Output to the Screen

Number Sense. I CAN DO THIS! Third Grade Mathematics Name. Problems or Examples. 1.1 I can count, read, and write whole numbers to 10,000.

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Introduction to Software Development (ISD) David Weston and Igor Razgon

4. Java Project Design, Input Methods

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Introduction to Computer Programming

Variables, Data Types, and Arithmetic Expressions Learning Objectives:

1 5 Integer Operations

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

MODULE 02: BASIC COMPUTATION IN JAVA

BCIS 3630 Dr. GUYNES SPRING 2018 TUESDAY SECTION [JAN version] GRADER COURSE WEBSITE

ASSIGNMENT 2. COMP-202A, Fall 2011, All Sections. Due: Monday, October 17th, 2011 (23:30)

Lesson 6 page 1. If you look at the bottom right of the Scratch color choices, you will see it say MORE BLOCKS in Purple.

ECS Baruch Lab 5 Spring 2019 Name NetID (login, like , not your SUID)

Transcription:

CS 170 Java Programming 1 Week 3: Objects, Input and Processing Learning to Create Objects Learning to Accept Input Learning to Process Data

What s the Plan? Topic I: Working with Java Objects Learning to create and control Turtle objects Topic 2: Processing and Input Input, creating objects, creating variables Processing, numbers, and calculations Using Math functions for complex processing

Topic 1 Creating and Controlling Objects Learn to Create Turtle Objects Control Your Turtle with Methods

Creating a Simulation Computers let us simulate things Buildings, factories, machines (rockets, cars), chips Do this by creating software models of the things we want to simulate and then writing programs to use them We need to define what kinds of objects we will want in our simulation and what they can do Classes define the types (data and behavior) Instances of the class (objects) act in the simulation

Computers as Simulators The computer is the Proteus of machines. Its essence is its universality, its power to simulate. Because it can take on a thousand forms and serve a thousand functions, it can appeal to a thousand tastes. -- Seymour Papert in Mindstorms

History of Turtles Seymour Papert at MIT in the 60s Developed the Logo language Focused on teaching children By teaching the computer to do something kids are thinking about thinking Develop problem solving skills Learn by constructing and debugging something Learn by making mistakes and fixing them

Using Turtles The Turtle class we'll use is part of several classes created at Georgia Tech called the MediaComp classes I've already added these to our version of DrJava You don't need the "book-classes" from the text

Creating Objects To create objects we ask a class to give us a new instance or object Class is like a cookie cutter It knows how much space each object needs (shape) Many objects can be created from the same class

Class as Object Factory We ask a class to create an object by using the keyword: new ClassName(value, value, ) We can also ask the class to initialize the object May pass arguments (data) to help initialize it

Your "IC" or "Lab" Document Use Word or OpenOffice to create a new document Save the file as IC03.doc (Office 97-2003 compatible) Place on your network U: drive or on a thumb drive Put your name and today's date at the top of the sheet Title it "CS 170 Lab Exercises Week 3" Exercise 3.1: start DrJava In the Interactions Pane type new World() Press Enter and shoot a screen-shot of the output

Creating Objects in Java Turtle objects live inside a World object Means we must create a World object first Typing new World() creates a new World object But you don't have any way to refer to it again We need a way to refer to the new object so we can send messages to it; we need to name or identify it!

Naming is Important When you get a new pet the first thing you do is name it Lets you refer to the new pet without saying: "Please take that dog we got yesterday for a walk." Instead, you can say "Please take Fifi for a walk." In programming we name things we want to refer to again Gives us a way to work with them Like the World object This is called declaring a variable You must declare a variable before you use it

Declaring a Variable To declare a variable we need to specify what kind or type of thing it is and give it a name Type name; OR Type name = value; OR Type name = new ClassName(v1, v2, ); The equal sign doesn t mean equal Copies "stuff" on the right into the variable on the left Let's look as some examples

Declaring Variables Exercise 3.2: create these variables and snap a pic. Specify the type and a name String name; World world1; int x; Can also give a starting value when you declare it String fullname = "Stephen Gilbert"; World world2 = new World(); int y = 0;

Variables as "Memory Boxes" A variable is like a box with a label on it. You can: put something into a box take something out of a box change what is in the box The size of the box restricts what you can store in it

Object and Primitive Variables Primitive variables allocate space based on their size The space is set to the variable s value Object variables allocate space for a reference to an object The variable contains a "serial number" that can be used to locate the actual object in memory. int a = 3 a 3 String s ="Hi"; s reference "Hi"

Limits on Declaring Variables You can't declare two variables with the same name! > World earth = new World(); > World earth = new World(); Error: Redefinition of 'earth' You can change what an object variable refers to > World earth = new World(); > earth = new World(); Exercise 3.3: assign values to world1, name and x.

Create Some Turtles Turtles must live inside a World object Supply the World when you create the Turtle Exercise 3.3: Create a Turtle object named tim tim = new Turtle(world1); Places tim inside the world1 object; snap a pic Exericise 3.4: Create a second Turtle named bill Place bill inside the world2 object. Snap a pic. Exercise 3.5: Create a third Turtle named sally Place sally inside world2 along with bill then snap

What Can Turtles Do? Turtles can go forward: tim.forward(); Tell them how far to move: sally.forward(50); Can turn left or right 90 degrees: bill.turnleft(); Turtles can also turn like this: tim.turn(50); A negative number turns counter-clockwise Can put their pen up or down: sally.penup(); Move to a specific location: bill.moveto(25, 50); First number x, second y, 0,0 in upper-left corner

Drawing a T Exercise 3.6: use a turtle to draw a large letter T Process Ask the Turtle object to go forward 100 Ask the Turtle object to pick up the pen Ask the Turtle object to turn left Ask the Turtle object to go forward 25 Ask the Turtle object to turn 180 degrees Ask the Turtle object to put down the pen Ask the Turtle object to go forward 50 Snap a picture when finished.

Topic 2 Input and Interactive Programs Learn to Create Interactive Programs

Interactive Programs So far, our programs have been static, not dynamic They work exactly the same each time they run We make our programs dynamic or interactive by having them process input supplied by the user Input can be commands (mouse, menu or keyboard) Input can also be data, which we'll store in variables The basic pattern for interactive programs: Ask the user to enter some data (called a prompt) Create a variable to hold the user's input Read the data and store it in the variable

The Greeter Program Our first program will be a dynamic variation of last week. Exercise 3.7: open Greeter.java in your week03 folder. Add your name, date; compile and run. Then, run Check and snap a picture

Greeter: String Input and Scanners For Greeter, we need a variable to hold the user's name when they supply it. What type should it be? Go ahead and add the variable Scanner reads numbers and strings from the keyboard Have to create a Scanner, just like creating a Turtle Scanner cin = new Scanner(System.in); Go ahead and add this Scanner variable as well.

Scanner Import Statements Compile your program. What happens? Package containing Scanner class is not automatically loaded when program starts Use import statement to add Scanner to program import java.util.scanner; Put at very top of your program. In Interactions Pane, anywhere before you use it

Reading the Input Scanner objects know how to read different types Variable must be the right type to hold the result fullname = cin.nextline(); // whole line word = cin.next(); // one word x = cin.nextint(); // an integer a = cin.nextdouble(); // double Place right after the prompt that asks the user for input. Remove "dummy data"; change println to print Exercise 3.8: run and shoot a screen-shot

Introducing Processing We now have input and output, but no processing Processing means converting input to output Can involve arithmetic or other operations In our program we want to change the output so that the user's name becomes part of the greeting Remember + concatenates or "pastes" strings together Exercise 3.9: complete the output line in Greeter, run the program and then run Check. Fix any errors and paste a screen-shot into your IC document.

CelsiusToFahrenheit Close Greeter and open CelsiusToFahrenheit As you can see, this is very similar: Have a prompt asking the user to enter a temperature Use the Celsius input to calculate the Fahrenheit output Combine the calculated value with the output text

Introducing Numbers Six of Java's eight built-in primitive types are numbers Two families: integers and floating-point Integers are whole numbers Real (floating-point) can have a fractional part Each family has different sizes: Integer has four: byte, short, int, long Real has two: float and double We'll usually use the int type for integers and the double type for real numbers

Variables and Input Exercise: create variables for both input and output Both should be type double Name them celsius and fahrenheit Note that by convention, variables use camelcase Exercise: create a Scanner variable to read the input Exercise: read the input value using your Scanner Make sure it appears after the prompt Change the prompt and remove the dummy data Exercise 3.10: run and shoot a screen-shot

Processing the Data How do we convert the Celsius temperature that the user entered into the Fahrenheit temperature? Here's the formula for calculating Fahrenheit We need to "translate" that into a Java expression An expression is just a calculation that produces a value which can then be used or stored in a variable Let's try this out in the Interactions Pane

What Are Expressions? An arithmetic expression uses operands (values) and operators (+ - * / %) to produce a numeric value (3 + 4) * 5 67 / 8 3.141592 * 5.0 * 5.0 In the Interactions Pane, you can type an expression and when you press Enter, DrJava will evaluate and print it

Interactive Arithmetic In the Interactions Pane evaluate the following values subtract 7 from 9 add 7 to 3 divide 3 by 2 multiply 5 by 10 find the remainder when 10 is divided by 3 Exercise 3.11: shoot a screen-shot of the interaction Evaluation order: parentheses, multiplicative, additive

Calculating Fahrenheit Let's try this in the Interactions Pane Create two double variables named c and f Set c to 100 Use the formula here to assign a value to f Display the value of f Why don't we get the right answer? (9 / 5) is 1 because 9 and 5 are integers

Integer Division Operations Integer division works like primary-school long division The quotient is calculated, remainder discarded The result, an integer, is truncated, not rounded The remainder operator returns the remainder part 12 % 7 is 5: 7 goes into 12 once, with 5 left over Algebra formulas (like you'll normally work with) assume fractions are real numbers Exercise 3.11: fix CelsiusToFahrenheit so that it passes all tests. Paste screenshot into IC03.

Using the Math Class Java's Math class is used for complex calculations Part of the java.lang package so you don't import it Methods for basic numeric operations Constants: Math.E and Math.PI Square root: Math.sqrt(double); Raise a number to a power Math.pow(double a, double b) a b

Finishing Up To complete your IC "lab" document: Complete Exercise 3.12 in the Processing Data lesson and the Exercises 3.13 at the end of the Math Functions lesson. Submit to Blackboard when done Reading for next week: Mediacomp: finish Chapter 3 and start Chapter 4 Gaddis: finish Chapter 1 start Chapter 2

Homework and Quiz Homework, Quiz and Assignments Deadline is Monday at noon Four homework problems Upload to Assignment Dropbox. Make sure to press Submit Proficiency Quiz 2: Basic IPO Problems Practice on IPO assignments (TipCalc, CircleStats) You will have ½ hour, assigned seating

Additional Credits Some material adapted from instructor materials created by B. Ericson to accompany Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, released under a Creative Commons 3.0 Attribution License.