F27SA1 Software Development 1 3. Java Programming 2 Greg Michaelson.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Expressions, Data Conversion, and Input
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2 Elementary Programming
Flow of Control Part 1: Selection
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
By Mr. Muhammad Pervez Akhtar
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
Primitive Data Types int is a primitive data type A primitive data type is one that stores only a single piece of data. TypeStorageDescription int 4 bytes+ve.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
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.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
Introduction to Algorithmic Processes CMPSC 201C Fall 2000.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
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.
CompSci 230 S Programming Techniques
Elementary Programming
Building Java Programs
Yanal Alahmad Java Workshop Yanal Alahmad
Java Programming: From Problem Analysis to Program Design, 4e
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Starting JavaProgramming
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2: Basic Elements of Java
Building Java Programs
MSIS 655 Advanced Business Applications Programming
Fundamentals 2.
Building Java Programs Chapter 2
CS150 Introduction to Computer Science 1
Chapter 2 Programming Basics.
Building Java Programs
Building Java Programs
CSC 1051 – Data Structures and Algorithms I
Building Java Programs Chapter 2
Building Java Programs
Presentation transcript:

F27SA1 Software Development 1 3. Java Programming 2 Greg Michaelson

Arithmetic operators expression ::= expression 1 operator expression 2 + == add 1+2  3 - == subtract 5-7  -2 * == multiply 3*4  12 / == divide & lose remainder 31 div 3  10 % == remainder from division - modulo 31 % 3  1

Arithmetic operators if both operands are int, use integer arithmetic if either operand is float / double use floating point arithmetic  66.2

Negation expression ::= operator expression unary operator - expression expression is a numeric type evaluate expression to value  minus value e.g

Brackets, order & precedence expression ::= ( expression 1 )  value from expression 1 evaluate expression from left to right precedence == order of applying operators (...) before - before * or / or % before + or –

Brackets, order & precedence 10+4*5   30 (10+4)*5  14*5   4-2  2 11-(7-2)  11-5   -13 -(6-7)  -(-1)  1

Constants if a value is to be used in many different places then: – declare it once as static final – i.e. only one instance which can’t be modified – identifier should be CAPITAL LETTERS Java convention – only ever use the identifier to change the value everywhere just change the declaration once

Numeric input for types other than String, must convert from character sequences Scanner methods int nextInt() return next int from Scanner object float nextFloat() return next float from Scanner object double nextDouble() return next double from Scanner object

Programming principles always tell user what’s happening – user is not programmer – programmer knows what program does, but user doesn’t – so program must always tell user what’s going on e.g. input – print to display to say what’s expected before input from keyboard e.g. output – print brief heading information before numbers – never print raw numbers!

Comments /* text */ – use text to remind you and other programmers what program sections do – compiler/computer ignores text – text can run over several lines always start program with header: /* your name & date course/laboratory/exercise details what program does */

Layout use space on page to indicate how sections of program are related GJM likes indentation – line up starts of lines between { and } – opening { on new line – after opening {, 2 spaces, then 3 spaces at start of subsequent lines until closing } – line up closing } under matching opening { matter of personal taste develop own style but be consistent!

Example: Pie shop $java Pie pie: £2.39 how many pies? 2 2 £2.39 = £4.78

Example: Pie Shop /* Greg Michaelson 27/9/10 F27SA1 Lecture 3 Pie Shop */ import java.util.*; class Pie { static final double PIE_PRICE = 2.39; public static void main(String [] argv) { Scanner input = new Scanner(System.in);

Example: Pie Shop System.out.println("pie: £"+PIE_PRICE); System.out.println("How many pies?"); int pieNo = input.nextInt(); double pieTotal = pieNo*PIE_PRICE; System.out.println (pieNo+" "+PIE_PRICE+" = "+pieTotal); }

Example: Take Away $java TakeAway samosa: £1.55 how many samosas? 3 3 £1.55 = £4.65 pie: £2.39 how many pies? 2 2 £2.39 = £4.78 total = £9.43

Example: Take Away /* Greg Michaelson 27/9/10 F27SA1 Lecture 3 Take away */ import java.util.*; class TakeAway { static final double SAMOSA_PRICE = 1.55; static final double PIE_PRICE = 2.39; public static void main(String [] argv) { Scanner input = new Scanner(System.in);

Example: Take Away System.out.println("samosa: £"+SAMOSA_PRICE); System.out.println("How many samosa?"); int samosaNo = input.nextInt(); double samosaTotal = samosaNo*SAMOSA_PRICE; System.out.println (samosaNo+" "+SAMOSA_PRICE+" = “+samosaTotal); System.out.println("pie: £"+PIE_PRICE); System.out.println("How many pies?"); int pieNo = input.nextInt(); double pieTotal = pieNo*PIE_PRICE; System.out.println (pieNo+" "+PIE_PRICE+" = "+pieTotal);

Example: Take Away System.out.println ("total = "+(samosaTotal+pieTotal)); } dreadful programming style! big block of code repeated code: – same actions for samosas and pies

Example: Take Away identify general Food class String name double price double total void findTotal(Scanner input) – prompt for & get number of food items from keyboard calculate & display total double getTotal() – return value of total

Example: Take Away make samosas & pies instances of Food need constructor to create instance Food(String name,double price) now need to initialise instance fields separately from declaring them

Assignment assignment changes value of declared variable statement ::=... | assignment assignment ::= identifier = expression; – variable must be declared – value must be of same type as for variable – evaluate expression to get a new value – set variable for identifier to new value use to: – reuse variable – set value of object field in constructor

Assignment int age = 56; age = age + 1; changes age to 57 int age = 56; int age = age + 1; declares two variables called age sets first to 56 and second to 57 allocates space for two variables called age ! can’t access first age as identifier always refers to second one!

Assignment evaluated from right to left! identifier 1 = identifier 2 ; sets identifier 1 to value of identifier 2 int twin1Age = 25; int twin2Age; twin2Age = twin1Age; – sets twin2Age to 25

Food object class Food { String name; double price; double total; Food(String name,double price) { this.name = name; this.price = price; } this == current object instance use to distinguish field identifier from parameter identifier double getTotal() { return total; }

Food object void findTotal(Scanner input) { System.out.println(name+": £"+price); System.out.println("How many "+name+" ?"); int no = input.nextInt(); total = price * no; System.out.println (no+" £"+price+" = £"+total); }

Example: Take Away 2 class TakeAway2 { public static void main(String [] argv) { Scanner input = new Scanner(System.in); Food samosa = new Food("samosa",1.55); Food pie = new Food("pie",2.39); samosa.findTotal(input); pie.findTotal(input); System.out.println ("Total £"+(samosa.getTotal()+pie.getTotal())); } no code repetition can easily add new items of food

Example: Take Away 2 void findTotal(Scanner input) {... int no = input.nextInt();... }... public static void main (String [] argv) { Scanner input = new Scanner(System.in);... samosa.findTotal(input); pie.findTotal(input);... } findTotal has a Scanner argument main declares Scanner input passed input to both calls to findTotal – so both calls use same input stream samosa.findTotal(input) called before pie.findTotal(input) – so number of samosas is input before number of pies

Programming principles if similar code sequences used in different places then generalise as class – identify common: variables  fields statements  methods keep object classes separate from class for program ( main ) that manipulates objects

Boolean type boolean type values true and false use to: – indicate whether or not some property holds e.g. likes pies: yes/no – represent two-value state e.g. switch: on/off

Example: Switch class Switch { boolean on; Switch(boolean on) { this.on = on;} void setOn(){ on = true; } void setOff(){ on = false; } boolean isOn{ return on; }

Logical operators: negation ! expression – unary expression must be boolean truth table – shows values of boolean expression for different values of operands expression ! expression falsetrue false

Example: Switch... void changeSwitch() { on = !on; }... Switch s1 = new Switch(true);  s1.on == true... 1.s1.changeSwitch();  s1.on == false 2.s1.changeSwitch();  s1.on == true 3.s1.changeSwitch();  s1.on == false

Logical operators: and expression 1 && expression 2 binary conjunction expression 1 & expression 2 must be boolean true if both operands are true otherwise false expression 1 expression 2 exp 1 && exp 2 false truefalse truefalse true

Logical operators: or expression 1 || expression 2 binary disjunction expression 1 & expression 2 must be boolean true if either operand is true otherwise false expression 1 expression 2 exp 1 || exp 2 false true falsetrue

Example: Switch Switch hallLight = new Switch(true); Switch stairLight = new Switch(false);......hallLight.isOn() || stairLight.isOn()  true || false  true... hallLight.changeSwitch(); stairLight.changeSwitch();......!hallLight.isOn() && stairLight.isOn()  not false && true  true && true  true