SOFTWARE AND PROGRAMMING 1 Lecture 2, 2011 Instructor: Prof. Boris Mirkin DCSIS, room 744, tel. 020 7631 6746 Labs: from 26/1,

Slides:



Advertisements
Similar presentations
SOFTWARE AND PROGRAMMING 1 Lecture 3: Ticketing machine: Constructor, method, menu Instructor: Prof. Boris Mirkin web-site
Advertisements

SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11& ) Lab: B43, MB321, MB536 6:00-7:30 (from ) [each student must have obtained.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
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.
03 Data types1June Data types CE : Fundamental Programming Techniques.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
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;
MSc IT Programming Methodology (2). MODULE TEAM Dr Aaron Kans Dr Sin Wee Lee.
Java Basics (continued)
Introduction to Information and Computer Science Computer Programming Lecture c This material (Comp4_Unit5c), was developed by Oregon Health and Science.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
SOFTWARE AND PROGRAMMING 1 Lecture: Gor B4 7:40-9:00 (from ) Lab: SH131, BBK536 6:00-7:30 (from ) [each student must have obtained access.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Lecture 2: Classes and Objects, using Scanner and String.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
SOFTWARE AND PROGRAMMING 1 Revision Lecture 11/5/2011: Review of concepts involved in lectures and exam Review of questions in previous exam papers (they.
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.
SOFTWARE AND PROGRAMMING 1 Lecture 7/5/8: Review of concepts involved in lectures and exam Lecture 14/5/8: Review of questions in previous exam papers.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
F27SA1 Software Development 1 3. Java Programming 2 Greg Michaelson.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: Ms Mihaela Cocea (from ) Room London Knowledge Lab Emerald.
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11& ) Lab: B43, MB321, MB536 6:00-7:30 (from ) [each student must have obtained.
SOFTWARE AND PROGRAMMING 1 Lecture: UCL BC57:30-9:00 (9& – from 6:00) Lab: SH 131, SH B12 6:00-7:30 (from ) (students will be assigned.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (11& – from 6:00) Lab: B43, MB321, MB536 6:00-7:30 (from ) EACH student must have obtained.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
SOFTWARE AND PROGRAMMING 1 Lecture: MB33 7:30-9:00 (except 11& ) Lab: B43, MB321, MB536 6:00-7:30 (from ) [each student must have obtained.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Decisions, Decisions, Decisions Conditional Statements In Java.
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: (from ) Ms Mihaela Cocea Room London Knowledge Lab Emerald.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
By Mr. Muhammad Pervez Akhtar
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
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.
Java I/O Basics MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh Bajaj,
SOFTWARE AND PROGRAMMING 1 Lecture 2, 2010 Labs start : DCSIS room 131 LAB SH room B29 Lecture EACH student must have obtained.
Java Basics (continued) Ms. Pack AP Computer Science A.
SOFTWARE AND PROGRAMMING 1 Advert : NO TEST1 on 7/02: TEST1 will be 14/02 Lab: SH131, BBK536 6:00-7:30 (from ) [each student must have obtained.
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
Information and Computer Sciences University of Hawaii, Manoa
SOFTWARE AND PROGRAMMING 1
Chapter 2 Basic Computation
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
User input We’ve seen how to use the standard output buffer
Chapter 2 Basic Computation
An Introduction to Java – Part I, language basics
Building Java Programs
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Just Enough Java 17-May-19.
Introduction to java Part I By Shenglan Zhang.
Presentation transcript:

SOFTWARE AND PROGRAMMING 1 Lecture 2, 2011 Instructor: Prof. Boris Mirkin DCSIS, room 744, tel Labs: from 26/1, 7.30 pm, in Room B12, UCL Cruciform Building Logins will be given to those attending Course Assistant: Lab/WebCT/Tests/Assignments: Mr Martin O’Shea (3) to formatting all tables.

2 Webpages Course web page at BlackBoard: ac.uk ac.uk Please check it regularly. It will be used for announcements and assignments. Another page, at an open-to-all web- site, functions with relevant materials too:

3 Concepts to keep in mind Compiler (javac.exe) and Interpreter (java.exe), should be on system’s path JDK and BlueJ for running Java Class (template) and Object (its instantiation); every Java program must be a class Variable and its type; primitive types Method (input-to-output operation) and its Parameters (inputs - with their types at method’s declaration)

4 Concepts for tonight Loops for, while (Have been taught 12/1, but are in this note set) Expressions Choice structure if/elseif/else Method Strings Math and random Input Using TextIO class Using Scanner

5 Type in Java Next few slides cover some material on unifying data types and expressions that was talked about at the previous lecture

6 Unifying type Look at A=6.0+5 What type of A can be? Can A be Integer? No way. A most senior type! Unifying type: float or double

7 Type casting The unifying type can be overridden by explicitly stating a type cast: Place the desired type result in parentheses followed by the variable or constant to be cast (int)  13 Example: int bankbalance=931786; float weeklybudget = (float) bankbalance /4; Another way: float weeklybudget = bankbalance /4.0;

8 Boolean expressions: true or false |, || or 5==(1+3+7) | a+b==b+a E1 E2 E1|E &, && and !not ==equal to <less than >greater than <=< or == >=> or == Always after arithmetic; If not sure, use parentheses (…): first performed inside

9 Condition int x=2; x+4*2 > 5true at what x is this false? int x=3; int y=1; x-4 == 1.5*(y+2) can this be true?

10 Precedence table

11 A simple program /* HelloWorld.java Purpose: printing a message to the screen */ class HelloWorld { // Each program is organised as a class public static void main(String[] args) { System.out.println("Hello World!"); } } // end of class HelloWorld /* Always Three Types of Elements ONLY: -comments -class (with modifiers) -methods (with modifiers & parameters/arguments)*/

12 More on Method Method in Java is a named set of instructions that transforms some input into an output. This is, actually, a machine implementation of the concept of algorithm which itself is a computational analogue to the mathematical concept of function. Static method: is shared by all instances.

13 Example of a method (1) Square function y = x 2 (an infinite Table) x y The table can be used for invoking a specific value, like, 7 2 = 49 or 10 2 = 100.

14 Example of a method (2) A Java method to calculate the square function: public int sq(int x){ return x  x;} To make it work, variables are needed: int sevs=sq(7); //puts 49 into sevs int tens=sq(10); // puts 100 into tens

15 Structure of a method modifiers return-type name ( parameter-list ) { statements; return variable/expression; //if return type is not void } Modifiers: –static - method/variable that belongs to class as whole and is shared by all instances –public - method/variable that is accessible from anywhere –private - method/variable that is accessible from only within the class Output’s typeInputs

16 HelloWorld with a method // Hello-world program to demonstrate BlueJ class Hello{ // Method that does the work of printing public void go() { System.out.println("Hello, world"); } // main method for working outside BlueJ public static void main(String[] args) {Hello hi = new Hello(); //instance hi.go(); //method in instance hi }

17 HelloWorld : WHY Why dots in System.out.println("Hello, world"); hi.go(); ? 1)To take method from a specific class instance 2)To take a class from a set of classes: Java is organised as a hierarchically structured set of classes in individual files

18 Loop for for(int var=1;var<=st;var=var+1) { do operations depending on var } var=var+1 is var++ Two types of parentheses: (loop control) and {body to do operations} Three items in control ( ): –initialising the counting variable once, –variable update, and –stop-condition Exit from the loop – only from within control ( … )

19 Loop for for(int var=1;var<=st;var++) % no ‘;’ here!!! { do operations depending on var } Two types of parentheses: (loop specified) and {body to do} The expression in loop control “()” consists of three items in this order: –initialising the counting variable once –stop-condition –variable update First, –var is initialised, –stop-condition is tested; if true, block {} is executed, if no, the program proceeds further on, after the block { } –control returns to ( ) After control returns to ( ), –var is updated; –stop-condition is checked; if true, block {} is executed, then control returns to ( ), if no, the program proceeds further on, after the block { }

20 HelloWorld N times BlueJ public class HelloN { int number; \\ variable declared public void go() { System.out.println("Hello, world"); } public HelloN(int howmany) {number=howmany; } \\constr to initialise object public void prrt() \\printing number times { for(int i=1;i<=number;i++) \\loop go(); System.out.println("ok"); }}

21 No { } in for-loop in HelloN Why? Let us add { }: where? Is there any difference between before and after “ok”?

22 Loop while: less rigid for(init; test; update){ statements } All three in the parentheses refer to a counter that is initialised, updated and tested over reaching the pre-specified threshold Structure of while loop contains same elements – init, test and update – but less rigid, not necessarily based on counter but rather on a condition; while’s structure: init; while(test){ statements; update } Similar elements: ( ), { }, initialisation, test condition (not necessarily involving the counter!), and update

23 Example: for (int K = 10; K > 1 ; K--) { //k-- is k=k-1; if (K < 7) { break; } // Stops execution of the loop else System.out.print(“ ” + K); } 1. What this loop does? 2. Can it be rewritten in the while format?

24 Example: answer 1 for (int K = 10; K > 1 ; K--) { if (K < 7) { break; } else { System.out.print(“ ” + K);} } What this loop does? Prints

25 Example: answer 2 int K = 10; while(K >1) { if (K< 7) break; else System.out.print(“ ” + K); K--; }

26 BlueJ HelloWorld N times public class HelloN { int number; \\ variable declared public void go() { System.out.println("Hello, world"); } public HelloN(int howmany) {number=howmany; } \\constr-r to initialise an object public void prrt()\\printing number times { for(int i=1;i<=number;i++) \\loop go(); System.out.println("ok"); } }

27 Three branching structures (1) Do under a condition; otherwise do nothing [if… structure] if(BooleanExpr) Statement or if(BooleanExpr) {Statements} (2) Do under a condition; otherwise do differently [if…else… structure] if(BooleanExpr) {Statements1} else {Statements2}

28 Java branching structure (3): (3)Several conditions to do differently [if…else if… … else if… else structure] if(BoolExpr1) Statement1; else if(BoolExpr2) \\and not BoolExpr1 Statement2; else \\ (not BoolExpr1) and (not BoolExpr2) Statement3; Note NO Bool. Exp at else

29 If/else example Ticket’s price is £5, 60+ concession £3, children 12 or less go for free Need a variable for the age, say YourAge, and the price, say Price; The fragment can be as: if (YourAge<=12) Price=0; else if (YourAge<=60) Price=5; else //note NO CONDITION to be put here Price=3;

30 Statements Assignment (followed by ;) Method call (followed by ;) if/ifelse/else (block, no ;) for/while loop (block, no ;) break (followed by ;)

31 Double loop with method class ATM{ public static void main (String[] args) { PrTab(2,4); } \\end main static PrTab(int rowsize, int columnsize){ for (int i1=1;i1<rowsize+1; i1++){ System.out.print(i1 + " ! "); for (int i2=1;i2<columnsize+1; i2++){ sum=i1+i2; System.out.print(sum +" ");} System.out.println();} }}\\end class

32 This produces: produces 1! ! ! Q: How to make the print look better? (See printing method in TicketMachine – next time.) Q: How to modify table to other ranges? Q: Make a MULTIPLICATION TABLE?

33 Input/Output TextIO class TextIO.java, added to the directory that contains your class, eases input of data from the keyboard To input an integer: int UsInput = TextIO.getInt(); Computer will wait for the user to type in an integer value to UsInput.

34 Input/Output TextIO class (2) public class PrintSquare { public static void main(String[] args) { int uInput; // the number to be input by the user int Squared; // the userInput, multiplied by itself System.out.print("Please type a number: "); uInput = TextIO.getInt(); Squared = uInput  uInput; //why product? System.out.print("The square is "+Squared); } // end of main() } //end of class PrintSquare

35 Input/Output TextIO class (3) Other TextIO methods: b = TextIO.getByte(); // value read is a byte i = TextIO.getShort(); // value read is a short j = TextIO.getInt(); // value read is an int k = TextIO.getLong(); // value read is a long x = TextIO.getFloat(); // value read is a float y = TextIO.getDouble(); // value read is a double a = TextIO.getBoolean(); // value read is a boolean c = TextIO.getChar(); // value read is a char w = TextIO.getWord(); // value read is a String s = TextIO.getln(); // value read is a String

36 Input/Output in Java The TextIO class contains static member methods TextIO.put() and TextIO.putln(), the same as System.out.print() and System.out.println(). TextIO can only be used in a program if TextIO is available to that program. It is not built into Java. From Java version on, there is a similar class in Systems.in: Scanner

37 Input with Scanner class(1) From Java version on, there is a similar class in System.in. Scanner(System.in): - import the java.util package in a line preceding the class, - then declare an instance of Scanner and - then use it for prompting the user to enter data (of a specified data type, preferably int, nextInt(), or double, nextDouble() ) from keyboard

38 Input with Scanner class (2) import java.util.* class PrintDot{ int num=0; public static void main(String[ ] args){ Scanner scap = new Scanner(System.in); System.out.println(“How many dots to print? “); num=scap.nextInt(); for (int ik=0; ik<num; ik++) System.out.print(‘.’); System.out.println(); } \\end of main\\end } \\end of class [ footnote: will not compile!!!]\\end

39 Using method with Scanner import java.util.* class PrintDot{ int number=0; public static void main(String[ ] args){ Scanner scap = new Scanner(System.in); System.out.println(“How many ampersands to print? “); number=scap.nextInt(); ppp(number); } \\end of main void ppp(nnn) { for (ik=0; ik<nnn; ik++) System.out.print(‘&’); System.out.println(); } \\end of ppp } \\end of class

40 Strings(1) Declaring a String Object String variable An object of the class String – The class String is defined in java.lang.String and is automatically imported into every program Create a String object by using the keyword new and the String constructor method String aGreeting = new String(“Hello”); or by assigning an actual string String aGreeting = “Hello”;

41 Strings(2) Comparing String Values Strings are never actually changed; instead new Strings are created and String variables hold the new addresses; A part of the Java system called the garbage collector discards the unused strings Strings are not numbers; arithmetic and logic Java operations are not applicable. To compare Strings, a number of methods are utilised: – equals() method i f s1 and s2 are declared and initialised as String: s1.equals(s2) true if s1 and s2 are exactly the same sequences of characters NEVER s1==s2 !!! This is wrong, == applies to numbers only.

42 Strings(3) Comparing String Values Try "HaHaHa ” "haHaHa"(2 differences) s1.length() number of characters in s1 charAt() method requires an integer argument which indicates the position of the character that the method returns s1.charAt(N) N-th character in s1 (starting from N=0) String ss= “Look at you!”; Q. What is ss.charAt(3)? ss.charAt(7)? ss.charAt(17)? [A. In respect, ‘k’, ‘ ’, and error]

43 Strings(4) s1.substring(N,M) part of s1 in positions N, N+1,..., M-1 (positions are numbered from 0 !!!) String ss= “Look at you!”; What is ss.substring(3,7)? Concatenation Concatenation - Joining strings, can be done with symbol + “45” + “36” = “4536”

44 Class Math (no need to import) Math.pi  =3.14…,the ratio of the circumference to its diameter Math.abs(a) a if a >= 0, or -a if a < 0 Math.log(a) the natural logarithm (base e) of number a Math.sqrt(a) square root of number a Math.pow(a,b)a b ; if b is an integer then a b =a  a  …  a (b times)

45 Math.random() pseudorandom number: double within interval [0.0, 1.0) (zero included, unity not) How to use it to generate a random integer between 1 and 6 (inclusive), to imitate casting a dice?

46 Casting a dice double aa=Math.random(); //aa, a real number between 0 and 1 int an= 6*aa; //a real number between 0 and 6 int rand=(int) an; // whole number between 0 and 5 int randw=rand+1; // whole number between 1 and 6 The same in one line: int randw= (int) (6*Math.random()+1);

47 Casting a dice question How to generate a random integer between 10 and 20 inclusive? Answer: int rdt= (int) (11*Math.random()+10); Another possibility: using class Random with import java.util.Random

48 This is what was covered tonight Primitive type casting Boolean expression, statements Concept of method – a touch Loop for, while in a method Double loop Choice structure if/elseif/else Input from keyboard classes String Math