COMP 202. Java in one week

Similar documents
COMP 202 Java in one week

COMP 202 Java in one week

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CS111: PROGRAMMING LANGUAGE II

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CS313D: ADVANCED PROGRAMMING LANGUAGE

Chapter. Let's explore some other fundamental programming concepts

Chapter 2: Data and Expressions

COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java Coding 3. Over & over again!

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Chapter 2: Data and Expressions

Chapter 1. Introduction

CEN 414 Java Programming

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

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

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

Full file at

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

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Chapter. Focus of the Course. Object-Oriented Software Development. program design, implementation, and testing

Chapter 2. Elementary Programming

Chapter 2 Elementary Programming

Programming with Java

A variable is a name for a location in memory A variable must be declared

Primitive Data, Variables, and Expressions; Simple Conditional Execution

ECE 122 Engineering Problem Solving with Java

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

CS111: PROGRAMMING LANGUAGE II

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Computational Expression

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Chapter 2 ELEMENTARY PROGRAMMING

Program Elements -- Introduction

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

REVIEW. The C++ Programming Language. CS 151 Review #2

Introduction to Java Applications

BASIC ELEMENTS OF A COMPUTER PROGRAM

Conditional Programming

2: Basics of Java Programming

CMPT 125: Lecture 4 Conditionals and Loops

2 rd class Department of Programming. OOP with Java Programming

Chapter 2: Data and Expressions

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Course Outline. Introduction to java

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

CS110: PROGRAMMING LANGUAGE I

CSC 1051 Data Structures and Algorithms I

Lecture Set 2: Starting Java

AP Computer Science Unit 1. Writing Programs Using BlueJ

Lecture Set 2: Starting Java

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

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

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CSC 1051 Data Structures and Algorithms I

Data Conversion & Scanner Class

Identifiers. Identifiers are the words a programmer uses in a program Some identifiers are already defined. Some are made up by the programmer:

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

Basic Computation. Chapter 2

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

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

Introduction to Computer Programming

Control Statements: Part 1

CS 302: Introduction to Programming

Chapter 2 Primitive Data Types and Operations. Objectives

AP Computer Science Unit 1. Programs

Chapter 3. Selections

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

4 WORKING WITH DATA TYPES AND OPERATIONS

Loops. CSE 114, Computer Science 1 Stony Brook University

Simple Java Reference

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

Computer Components. Software{ User Programs. Operating System. Hardware

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Zheng-Liang Lu Java Programming 45 / 79

Chapter 4 Introduction to Control Statements

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CSC 1051 Data Structures and Algorithms I

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Oct Decision Structures cont d

Object Oriented Programming with Java

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Classes and Objects Part 1

Transcription:

COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week

The Java Programming Language A programming language specifies the words and symbols that we can use to write a program A programming language employs a set of rules that dictate how the words and symbols can be put together to form valid program statements Java was created by Sun Microsystems, Inc. It was introduced in 1995 and has become quite popular It is an object oriented language COMP 202 Java in 1 week 2

Java Program Structure In the Java programming language: A program is made up of one or more classes A class contains one or more methods A method contains program statements Statements are the actual commands you issue These terms will be explored in detail throughout the course A Java program always contains a method called main This is where the program starts COMP 202 Java in 1 week 3

Calculator I: add two Integers QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. COMP 202 Java in 1 week 4

Calculator I: add two Integers import java.util.scanner; public class AddTwoIntegers public static void main (String [] args) int input1, input2, output; Scanner scan = new Scanner(System.in); // read in the values System.out.println("Add: Type the first integer:"); input1 = scan.nextint(); System.out.println("Add: Type the second integer:"); input2 = scan.nextint(); // perform calculation output = input1 + input2; System.out.println("The sum is: " + output); COMP 202 Java in 1 week 5

Java Program Structure // comments about the class public class MyProgram class body class header : The name of the class Important: The class header name MUST be the same name as the file name: MyProgram.java Comments can be added almost anywhere COMP 202 Java in 1 week 6

Java Program Structure // comments about the class public class MyProgram // comments about the method public static void main (String[] args) method body method header COMP 202 Java in 1 week 7

Identifiers Identifiers are the words a programmer uses in a program. They are used to give names to things. An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive, therefore Result and result are different identifiers COMP 202 Java in 1 week 8

Identifiers Sometimes we choose identifiers ourselves when writing a program (such as input1, AddTwoIntegers) Sometimes we are using another programmer's code, so we use the identifiers that they chose (such as println) Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way main, class, public, COMP 202 Java in 1 week 9

More on println println takes one input a character string: println( hello world ); the value of a variable: println(output); the combination of both: println( The sum is + output); We will understand the exact semantics behind this soon COMP 202 Java in 1 week 10

Formatting and Errors QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. example2.java COMP 202 Java in 1 week 11

import java.util.scanner; Formatting and Errors public class AddTwoIntegersBad public static void main (String [] args) int input, input2; Scanner scan = new Scanner(System.in); input1 = scan.nextint(); input2 = scan.nextint() output = input1 + input2;system.out.println("the sum is: " + output); COMP 202 Java in 1 week 12

Programming Errors A program can have three types of errors The compiler will find problems with syntax and other basic issues (compile time errors) If compile time errors exist, an executable version of the program is not created A program may run, but produce incorrect results (logical errors) output = input1 input2; A problem can occur during program execution, and causes a program to terminate abnormally (run time errors) Divide by zero Wrong data type COMP 202 Java in 1 week 13

Development Life Cycle Debugging Write code Syntax Errors Compiler 0 errors Errors may take a long time to debug! Logic and run time errors Run program Important Note: When you compile for the first time and see the 150 errors, do not despair. Only the first 1 or 2 errors are relevant. Fix those and compile again. There should be fewer errors (like 50). Repeat until no errors. COMP 202 Java in 1 week 14

Syntax and Semantics The syntax rules of a language define how we can put symbols, reserved words, and identifiers together to make a valid program (see appendix L) The semantics of a program statement define what that statement means (its purpose or role in a program) A program that is syntactically correct is not necessarily logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do COMP 202 Java in 1 week 15

Calculator II: Choosing the right data type Integer: 4, 3, 2, 1, 0, 1, 2, 3, Real Number: number that can be given by an infinite decimal representation (e.g, 3.237654 ) Floating point number: approximation of a real number needs only finite space (fits in a cell or set of cells) data type in Java (for now): double COMP 202 Java in 1 week 16

Calculator II: Choosing the right data type Integer vs. double QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. COMP 202 Java in 1 week 17

Calculator II: Choosing the right data type Integer vs. double import java.util.scanner; public class AddTwo public static void main (String [] args) double input1, input2, output; Scanner scan = new Scanner(System.in); // read in the values System.out.println("Add: Type the first number:"); input1 = scan.nextdouble(); System.out.println("Add: Type the second number:"); input2 = scan.nextdouble(); // perform calculation output = input1 + input2; System.out.println("The sum is: " + output); COMP 202 Java in 1 week 18

Data Type compatibility If you try to assign a double value to a variable of type int, you get a run time error If you try to assign an int value to a variable of type double, an automatic conversion occurs COMP 202 Java in 1 week 19

Constants A constant is an identifier that is similar to a variable except that it holds one value for its entire existence The compiler will issue an error if you try to change a constant In Java, we use the final modifier to declare a constant final double PI = 3.14; Constants: give names to otherwise unclear literal values facilitate changes to the code More precision required: change PI only once to 3.14159 prevent inadvertent errors COMP 202 Java in 1 week 20

Calculator III: Constants import java.util.scanner; public class Circle public static void main (String [] args) double radius, circumference, area; final double PI = 3.14; Scanner scan = new Scanner(System.in); // read in the radius System.out.println("Enter radius:"); radius = scan.nextdouble(); // perform calculation circumference = 2 * radius * PI; area = radius * radius * PI; System.out.println("The circumference is: " + circumference); System.out.println("The area is: " + area); COMP 202 Java in 1 week 21

Arithmetic Expressions An expression is a combination of operators and operands radius * radius * PI Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition x + y Subtraction x y Multiplication x * y Division x / y Remainder x % y Negative x If either or both operands to an arithmetic operator are floating point (double), the result is floating point (double) COMP 202 Java in 1 week 22

Division with Integers If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) The remainder operator (%) returns the remainder after dividing the second operand into the first Example 1: int numhours = 52; int fulldays = numhours / 24; 2 int remaininghours = numhours % 24; 4 Division by 0 Produces run time error Program has to avoid it COMP 202 Java in 1 week 23

Calculator IV: Division QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. COMP 202 Java in 1 week 24

Calculator IV: Division import java.util.scanner; public class DivisionInt public static void main (String [] args) int nominator, denominator, output, remainder; Scanner scan = new Scanner(System.in); // read in the input System.out.println("Enter nominator:"); nominator = scan.nextint(); System.out.println("Enter denominator:"); denominator = scan.nextint(); // check correctness of input if (denominator == 0) System.out.println("The denominator may not be 0"); else // perform calculation output = nominator / denominator; remainder = nominator % denominator; System.out.println("The result is: " + output); System.out.println("The remainder is: " + remainder); COMP 202 Java in 1 week 25

If else statements A statement that allows a program to choose an action depending on the value of a boolean expression Example: if (balance > amount) balance = balance amount; else System.out.println( You cannot withdraw more money than you have ); System.out.println( your balance is: + balance); If the value of the variable balance is larger than the value of the variable amount, the amount is subtracted from the balance Otherwise the user is informed that the subtraction cannot be done In any case, the value of the balance is printed COMP 202 Java in 1 week 26

Boolean Expression An expression that evaluates either to true or to false Named after George Boole, inventor of the Boolean Algebra (we will discuss it in more detail later) Similar concept in natural language the traffic light is red This expression is either true or false COMP 202 Java in 1 week 27

Comparison Boolean Expressions often contain comparisons; if (denominator == 0) If the denominator is zero Note the difference of comparison == to assignment = One of the most common errors If (denominator!= 0) If the denominator is not zero if (balance > amount), if (balance < amount) If the balance is larger / smaller than the amount If (balance >= amount) If the balance is larger or equal to the amount If (balance <= amount) If the balance is smaller or equal to the amount COMP 202 Java in 1 week 28

The simple if then else Statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, not both COMP 202 Java in 1 week 29

Block Statements Several statements can be grouped together into a block statement A block is delimited by braces (... ) A block statement can be used wherever a statement is called for in the Java syntax For example, in an if else statement, the if portion, or the else portion, or both, could be block statements Task: rewrite the division program with comparison if (denominator!= 0) COMP 202 Java in 1 week 30

Calculator V: Add five numbers QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. COMP 202 Java in 1 week 31

Calculator V: Add five numbers import java.util.scanner; public class AddFive public static void main (String[] args) double input1, input2, input3, input4, input5, output; Scanner scan = new Scanner(System.in); // read in the input System.out.println("Enter first number:"); input1 = scan.nextdouble(); System.out.println("Enter second number:"); input2 = scan.nextdouble(); System.out.println("Enter third number:"); input3 = scan.nextdouble(); System.out.println("Enter fourth number:"); input4 = scan.nextdouble(); System.out.println("Enter fifth number:"); input5 = scan.nextdouble(); // perform calculation output = input1 + input2 + input3 + input4 + input5; System.out.println("The result is: " + output); COMP 202 Java in 1 week 32

Calculator VI: add 10 numbers QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. COMP 202 Java in 1 week 33

Calculator VI: add 10 numbers import java.util.scanner; public class AddTen public static void main (String [] args) double input; double output = 0; int counter; Scanner scan = new Scanner(System.in); // read in the values in a loop and incrementally perform calculation counter = 1; while (counter <= 10) System.out.println("Enter number:"); input = scan.nextdouble(); output = output + input; counter = counter + 1; System.out.println("The sum is: " + output); COMP 202 Java in 1 week 34

The while loop A loop allows us to execute a statement or a block of statements repetitively Body of the loop: the block of statements contained in the loop (executed repetitively) Iteration: one execution of body of the loop The body is executed repeatedly as long as the condition after the while evaluates to true If the condition never evaluates to true, then the loop is never executed COMP 202 Java in 1 week 35

The While loop syntax while is a reserved word while ( condition ) statement1; statement2; If the condition is true, the statement is executed. Then the condition is evaluated again. The statement is executed repetitively until the condition becomes false. COMP 202 Java in 1 week 36

Calculator VII: Adding an arbitrary amount of numbers QuickTimeª and a TIFF (LZW) decompressor are needed to see this picture. COMP 202 Java in 1 week 37

Calculator VII: Adding an arbitrary amount of numbers import java.util.scanner; public class AddArbitrary public static void main (String[] args) double input; int iterations; double output = 0; int counter; Scanner scan = new Scanner(System.in); System.out.println("Indicate the number of inputs:"); iterations = scan.nextint(); // read in the values in a loop and incrementally perform calculation counter = 1; while (counter <= iterations) System.out.println("Enter number:"); input = scan.nextdouble(); output = output + input; counter = counter + 1; System.out.println("The sum of the "+ iterations +" numbers is: " + output); COMP 202 Java in 1 week 38

Classes So far, we have used some existing classes: Scanner: Allows us to read from keyboard: nextint, nextdouble, System.out Allows us to print information to the screen: println We call the operations that we can perform methods So far, we have developed a set of own classes Division, AddArbitrary, But are these conceptually classes? They are rather methods of a class calculator! COMP 202 Java in 1 week 39

The calculator class Provides methods for Addition, subtraction, Expects repetitively input from user User must indicate type of operation (addition, subtraction, ) User must indicate input Calculator performs operation Calculator exits if user does not want to have further computation COMP 202 Java in 1 week 40

Structure Methods main Addition (similar to main method of our AddArbitrary Class before) Division (similar to main method of our Division Class before) COMP 202 Java in 1 week 41

main Method main get type of operation wanted by user 0: exit 1: add 2: divide While (type!= 0) If (type == 1) Call Addition method If (type == 2) Call Division method Make sure no other input is provided Get next type of operation wanted by user COMP 202 Java in 1 week 42

Summary Variables, variable assignments, expressions are the fundamental building blocks Variables can have different data types So far integer and floating point We can perform basic operations on variables +,, *, / If then else control when certain statements are executed While loops execute statements repetitively concept of a class bundle related functionality COMP 202 Java in 1 week 43