CompSci 001 5.1 Today’s topics Parsing Java Programming Reading Great Ideas, Chapter 3 & 4.

Slides:



Advertisements
Similar presentations
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Advertisements

Chapter 10 Introduction to Arrays
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 3: Data Types and Operators JavaScript - Introductory.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
CompSci Today’s topics Java Review Just a bunch of headings meant to trigger questions A contraction of previous notes Upcoming Midterm Exam Reading.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
A Computer Science Tapestry 3.1 Programs that Respond to Input l Programs in chapters one and two generate the same output each time they are executed.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Decision Making in Programs.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
CompSci Arrays  Aggregate data type  Deal with items of same type  Lists of words  Numbers  Analogies  Mailboxes in post office  CD racks.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CPS Topics l Networks revisited l Java intro l Decision Trees l Problem solving and computing with numbers l Upcoming ä Numeric computation Course.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
CompSci Today’s topics Parsing Java Programming Notes from Tammy Bailey Reading Great Ideas, Chapter 3 & 4.
JavaScript, Fourth Edition
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
Operator precedence.  Evaluate a + b * c –multiplication first? a + (b * c) –addition first? ( a + b) * c  Java solves this problem by assigning priorities.
1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
A Computer Science Tapestry 3.1 Programs that Respond to Input l Programs in chapters one and two generate the same output each time they are executed.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Topic 4 Expressions and variables Based on slides bu Marty Stepp and Stuart Reges from "Once a person has understood.
Today’s topics Java Input More Syntax Upcoming Decision Trees More formal treatment of grammers Reading Great Ideas, Chapter 2.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 7: Expressions and Assignment Statements
Chapter 7: Expressions and Assignment Statements
Java Programming: From Problem Analysis to Program Design, 4e
Arithmetic operations, decisions and looping
Building Java Programs
Building Java Programs
Building Java Programs Chapter 2
Building Java Programs
ICT Gaming Lesson 3.
Chapter 2 Programming Basics.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Primitive Types and Expressions
Building Java Programs Chapter 2
Chap 7. Advanced Control Statements in Java
Programs that Respond to Input
Building Java Programs
Building Java Programs
Problem 1 Given n, calculate 2n
Presentation transcript:

CompSci Today’s topics Parsing Java Programming Reading Great Ideas, Chapter 3 & 4

CompSci Robots l Java: Learning to Program with Robots à Based on Rich Pattis’ Karel the Robot à Teaches basic Java concepts in the context of graphical world Objects and methods Decomposition and abstraction l World à Cities with streets and avenues à Things that can sit at particular intersections, be picked up, and put down à Robots that can move around cities and manipulate Things

CompSci What can Robots do? l Objects have various methods à Services they provide moveMove forward one block. It continues to face the same direction. If the way is blocked by a wall, the robot will "break" into pieces. turnLeft Pivots 90  to the left. The robot remains on the same corner. pickThingPick up one thing from the corner on which it is standing and add it to its backpack. If there is no thing to pick up, the robot will "break" into pieces. putThingTake one thing out of the robot’s backpack and put it on the corner. If there is no thing in the robot's backpack, the robot will "break" into pieces. getAvenueReturns the avenue that the robot is currently at. getStreetReturns the street that the robot is currently at. getDirectionReturns the direction the robot is facing

CompSci Constructing a robot

CompSci Calling a method l Objects

CompSci Decision trees l If-Then statements if (logical expression) { “true” actions } l If-Then-Else statements if (logical expression) { “true” actions } else (logical expression 2) { “false” actions } l Logical expressions à analogous to yes or no questions  true or false Statements that are true à (5 < 7) à (100 == 100) à (100 != 10) à (10 <= 10) Statements that are false à (-2 > -1) à (10 != 10)

CompSci A decision tree He received the Physics Price in Try A. Solzhenitsyn, Literature Look up the Peace Prize in Try the Medicine Prize in Would you prefer a humanitarian? Would you like to read about a scientist? Would you like to read about Einstein?

CompSci More Java Syntax l Assignment statement variable = expression; l Method invocation à Also called function or procedure à Invoking also called “calling” a function à Methods can take arguments button.setText(“This text is an argument”); init() l Variable declaration VariableType variableName; Button choice;

CompSci Java Details l Java tutorial 1. Do “Your First Cup of Java” and create your First Applet 2. Go to “Learning the Java Language” and read “Language Basics” l Variable: an item of data named by an identifier l Operators à Arithmetic à Relational and conditional à Assignment à Other l Expression: a series of variables, operators, and method calls that evaluates to a single value

CompSci Dealing with numbers Primitive data type: int  Does not require a new statement to create à Primitive types not classes à Must declare à Should initialize (Java sets to 0) à Other primitive types include: boolean, char, double l Operations using integers  +, -, *, /, % à Operator Precedence

CompSci Some arithmetic details l Java adheres to traditional order of operations à * and / have higher precedence than + and – int x = * 6; int y = (3 + 5) * 6; à Parentheses are free, use them liberally l Arithmetic expressions are evaluated left-to-right in the absence of parentheses int x = 3 * 4 / 6 * 2; int y = (3*4)/(6*2); l There are limits on int and double value, be aware of them.

CompSci Types for Numbers l The type String is not a built-in type, technically it’s a class l There are many numerical types in Java We’ll use two  int, represents integers: {…-3,-2,-1,0,1,2,3,…} Conceptually there are an infinite number of integers, but the range is limited to [-2 31, ] or [Integer.MIN_VALUE,Integer.MAX_VALUE] A lternatives? Why is range limited?  double, represents real numbers like ,  2 Not represented exactly, so expressions like 100*0.1 may yield unexpected results Double precision floating point numbers, another type float exists, but it’s a terrible choice (generates poor results)

CompSci GIGO: program as good as its data? l In calculations involving floating point numbers it’s easy to generate errors because of accumulated approximations:  What is ?  When is (x + y) + z different from x + (y + z) ? The type int is severely constrained on 16-bit computers, e.g., running DOS, largest value is 32,767 ( )  Even on 32-bit machines, how many seconds in a millennium? 60*60*24*365*1000, problems? à On UNIX machines time is measure in seconds since 1970, problems?  What was Y2K all about?

CompSci What arithmetic operations exist? l Syntax and semantics for arithmetic operations  Addition, subtraction: + and –, int and double x + y d –  Multiplication: *, int and double 23 * 4 y * 3.0 d * 23.1 * 4  Division: /, different for int and double 21 / 4 21 / 4.0 x / y  Modulus: %, only for int 21 % 4 17 % 2 x % y l Mixed type expressions are converted to “higher” type à Associativity of operators determines left-to-right behavior l Use parentheses liberally  Without () use operator precedence, *,/, % before +,-

CompSci Dealing with text l Strings are a class and not a primitive datatype l Declaration: String message; l String Constants “Good Morning World!” l String Assignment message = "It's Friday";

CompSci Manipulating Strings l Methods for manipulation int length() int indexOf(String st) String substring(int start, int end) l Getting String Data from user  The TextField class has getText () method à Use: message = mg.getText(); where mg is a TextField and message is a String

CompSci Evaluating expressions l Order of precedence l Automatic type conversion à Values of one type are promoted to another compatible type as part of the computation process You can convert T f degrees Fahrenheit to T c degrees Celsius using the formula: T c = (5/9)*(T f -32) l Given the following expression: double Tc = (Tf – 40.0) * (5/9) If Tf is –40.0 what is Tc? error 5. unknown Operators Associativity Type () left to rightParentheses * / % left to rightMultiplicative + - left to rightAdditive >= left to rightRelationals == != left to rightEqualities = right to leftAssignment

CompSci More expressions int n = * ; What is n? error int n = 12 + “hello” unknown 5. errror int x = 8 * (7 – 6 + 5) % ( / 2) – 1; l What is x? error 6. something else

CompSci Repeating code l Repeating code is bad l Writing repetitive code is tedious l Debugging repetitive code is hard l Avoid repeating code through: à Subroutines/methods à Loops

CompSci Loops l If statements need to repeat, then you probably need a loop l Describe portion of program as: à Repeat à Continue until à For each value from 1 to n à For every object of a set, do something l We have already used iteration by using the buttons à How?

CompSci Problems l We want to: à Print out all numbers from 0up to 100 incrementing by 0.5 each time à Sum up the numbers from 1 to 100 à … l New Java syntax  New object type TextArea which is basically a big scrolling textbox  tArea is 80 character wide and 20 rows high text box with 20 rows TextArea tArea = new TextArea(20,80);  Add characters to the end of the TextArea using append tArea.append(“Hello\n”);  ‘\n’ is called a newline character which moves the next character to the next line

CompSci Anatomy of a while loop l While loops are one way to get rid of repetitive code l Print out numbers up to 100 by increments of 0.5 x  0 x  x print x x < 100 true false x = 0.0; while (x < 100) { x = x + 0.5; tArea.append(“x = “ + x); tArea.append(“\n”); }

CompSci Another loop l Summing the numbers 1 … 100 int sum = 0; int k = 0; while (k < 100) { k = k + 1; sum = sum + 1; } l Other Loop designs à Count down à Stopping and starting at computed values à Data dependent loop

CompSci Functions/Methods l Function example: distance from point (x,y) to origin l Function declaration à Name of the function à Type of each argument to the function with a descriptive name for each argument à The type of value a function returns

CompSci Function calling mechanics 1. The value of each argument are computed 2. The value of each argument is copied into the corresponding formal parameter 3. The statements in the function body are evaluated until a return statement appears 4. The value of the return expression is evaluated 5. The calling program continues, with the returned value substituted in place of the call

CompSci Functions can return strings String WeekDay(int day) { if (0 == day) { return "Sunday"; } else if (1 == day) { return "Monday"; } else if (2 == day) { return "Tuesday"; } else if (3 == day) { return "Wednesday"; } … } l Shorter (code) alternatives? à Is shorter better? l What function call looks like? String dayName; int dayNum = 4; dayName = WeekDay(dayNum); l Which is/are ok? Why? result.setText(WeekDay(5)); int j = WeekDay(0); result.setText(WeekDay(2.1)); String s = WeekDay(22); WeekDay(3);

CompSci Think about it Puzzle: Toggling Frogs à You have 100 light switches, numbered 1-100, and 100 frogs, also numbered à Whenever a frog jumps on a light switch, it toggles a light between on and off. All lights are initially off. frog #1 jumps on every light switch (ie turning them all on). frog #2 jumps on every 2nd light switch, toggling some of them back off.... frog #k jumps on every kth light switch.  After 100 frogs, which lights are on? Game: Don’t be last à You and a friend have a stack of 10 coins. à On each person's turn, they remove either 1 or 2 coins from the stack. à The person who removes the last coin wins. à What is a winning strategy? Should you go first or second?

CompSci Arrays l Aggregate data type l Deal with items of same type à Lists à numbers à words … l Analogies à Mailboxes in post office à CD racks with slots l Simplifies naming l Allows use of loops l Required for many mathematical and statistical problems l Multiple elements or cells

CompSci Using arrays l subscript or index to access element x[5] = 20; foo.setText(“Result is " + x[5]); l Often used in loops int k = 0; sum = 0; while ( k < 10 ) { k = k + 1; sum = sum + name[k]; }

CompSci l Declaration double weights[]; l Definition weights = new double[50]; l Combine double weights[] = new double[50]; int num[] = new int[6]; num[1] = 21; num[5] = 13; Creating Arrays ???????21???13

CompSci Arrays & Loops int k = 2; while(k<6) { num[k] = k*k; k = k+1; } ?