MSc IT Programming Methodology (2). number name number.

Slides:



Advertisements
Similar presentations
18 January 2013Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Advertisements

Programming Methodology (1). public class Hello { public static void main(String[] args) { System.out.println("Hello world"); } } Hello world.
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the.
Programming Methodology (1). Implementing Methods main.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Computer Programming Lab(7).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Strings in Java 1. strings in java are handled by two classes String &
Strings Testing for equality with strings.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
AP Computer Science TOPICS TO DISCUSS.equals() == instanceof operator compareTo Interfaces Abstract Classes.
1 Various Methods of Populating Arrays Randomly generated integers.
Computer Programming Lab 8.
Java Strings in 10 minutes
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Implementing Classes Learning objectives By the end of this lecture you should be able to: design classes using the notation of the Unified Modeling Language.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
© The McGraw-Hill Companies, 2006 Chapter 6 Classes and objects.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
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.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
MSc IT Programming Methodology (2). Oblong EasyScanner BankAccount.
ITI 1120 Lab #7. Agenda Topics in this lab: –Methods & Arrays –Library classes –Testing (JUnit) –Strings In this lab, you are going to create your own.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Introduction to Java Java Translation Program Structure
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
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.
Introduction to programming in java
Basic concepts of C++ Presented by Prof. Satyajit De
CSC111 Quick Revision.
Lecture 3 John Woodward.
Data Structures and Algorithms revision
Chapter 2 Elementary Programming
INPUT STATEMENTS GC 201.
Chapter Three - Implementing Classes
Chapter 7: Strings and Characters
Introduction to Java Programming
Introduction to Object-Oriented Programming
Presentation transcript:

MSc IT Programming Methodology (2)

number

name number

name number balance

abbey name number balance

name number balance abbey

deposit abbey

deposit withdraw abbey

getBalance deposit withdraw abbey

getBalance deposit withdraw abbey

BankAccount

abbey BankAccount

abbey halifax BankAccount

Class abbey halifax

Class object

Classes and objects Learning objectives explain the meaning of the term object-oriented; explain the concept of encapsulation; explain the terms class and object; create objects in Java; call the methods of an object; Use a number of methods of the String class; create and use arrays of objects.

Object-oriented programming…

Classes….

Student data methods Class objects ? s1 s2 s3 s4

Student data methods Class objects ? s1 s2 s3 s4 Encapsulation: The hiding of data within a class

How do you create objects from a Class ?

Object creation is a two-step process:

STEP 1: Declare object type.

Student data methods ? s1 s1;Student Class object

The effect on computer memory of declaring an object……

Student s1 ; Computer MemoryJava Instructions s1 ? Reference variable

Student s1 ; Computer MemoryJava Instructions s1 null Reference variable

STEP 2: Allocating memory to store the object data!

This is sometimes called instantiating an object!

Student data methods ? Class s1 object Student( )String, String A constructor method is required to generate object data from a class s1 = newStudent ( );“071202”, “Kans”

The effect on computer memory of instantiating an object……

Student s1 ; Computer Memory Java Instructions s1 This is the space for the new Student object s1 = new Student (“071202”, “Kans”); null

You can combine steps 1 & 2!

s1Student s1 = newStudent ( “071202”, “Kans”); ; = new Student (”071202”, “Kans”);

You can instantiate many objects from one Class !

Robot ? moveRight(int) moveLeft(int) moveUp(int) moveDown(int) Robot( )int, int Robot r1; r1 = new Robot(5, 50); Robot r2; r2 = new Robot(10, 2);

Calling the methods of another class….

Robot ? moveRight(int) moveLeft(int) moveUp(int) moveDown(int) Robot( )int, int Robot r1; r1 = new Robot(5, 50); Robot r2; r2 = new Robot(10, 2);

Robot ? moveRight(int) moveLeft(int) moveUp(int) moveDown(int) Robot( )int, int Robot r1; r1 = new Robot(5, 50); Robot r2; r2 = new Robot(10, 2); r1.moveRight(20); r2.moveDown(25);

Revisiting the Scanner class ……

To create a Scanner object we call the Scanner constructor: Scanner sc = new Scanner (System.in);

Scanner methods…..

int x = sc.nextInt(); double y = sc.nextDouble(); char reply = sc.next().charAt(0); this is a String methodthis is a String object

The String class

The String class is different from all other classes in Java. We can create String objects without a call to a constructor: String day = “Wednesday”;new String (“Wednesday”);

To obtain a string from the keyboard you can use the next method of Scanner day = sc.next();

String methods ……

charAt Accepts an integer and returns the character at that position in the string. Note that indexing starts from zero, not 1! An item of type int An item of type char length Returns the length of the string. None An item of type int substring Accepts two integers (eg m and n) and returns a copy of a chunk of the string, from position m to position n-1. Two items of type int A String object concat Accepts a string and returns a new string consisting of the that string joined to the end of the original string. A String object MethodDescriptionInputsOutput

toUpperCase Returns a copy of the original string, all upper case. None A String object toLowerCase Returns a copy of the original string, all lower case. None A String object compareTo Accepts a string and compares it to the object's string. It returns zero if the strings are identical, a negative number if the object's string comes first in the alphabet, and a positive number if it comes later. A String object An item of type int. equals Accepts an object and compares this to this to the string. It returns true if these are identical, otherwise returns false. An object of any class A boolean value. MethodDescriptionInputsOutput

import java.util.*; public class StringTest { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); String str = new String(); System.out.print("Enter a string: "); str = sc.next(); System.out.println("The length of the string is " + str.length()); System.out.println("The character at position 3 is " + str.charAt(2)); System.out.println("Characters 2 to 4 are " + str.substring(1,4)); System.out.println(str.concat(" was the string entered")); System.out.println("This is upper case: " + str.toUpperCase()); System.out.println("This is lower case: " + str.toLowerCase()); } } ;

Enter a string:Europe The length of the string is 6 The character at position 3 is r Characters 2 to 4 are uro Europe was the string entered This is upper case: EUROPE This is lower case: europe RUN import java.util.*; public class StringTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = new String(); System.out.print("Enter a string: "); str = sc.next(); System.out.println("The length of the string is " + str.length()); System.out.println("The character at position 3 is " + str.charAt(2)); System.out.println("Characters 2 to 4 are " + str.substring(1,4)); System.out.println(str.concat(" was the string entered")); System.out.println("This is upper case: " + str.toUpperCase()); System.out.println("This is lower case: " + str.toLowerCase()); }

Comparing strings …..

When checking two strings for equality use the equals method!

Do not use the equality operator (==)

if(firstString == secondString) { // more code here } String firstString = “Hello”; String secondString = “Goodbye”;

if(firstString == secondString) { // more code here } String firstString = “Hello”; String secondString = “Goodbye”;

if(firstString.equals(secondString)) { // more code here } String firstString = “Hello”; String secondString = “Goodbye”;

if(firstString.equals(secondString)) { // more code here } String firstString = “Hello”; String secondString = “Goodbye”;

When comparing two strings alphabetically use the compareTo method!

import java.util.*; public class StringComp { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); String string1, string2; int comparison; System.out.print("Enter a String: "); string1 = sc.next(); System.out.print("Enter another String: "); string2 = sc.next(); comparison = string1.compareTo(string2); // check comparison } }

if (comparison < 0) { System.out.println(string1 + " comes before " + string2 + " in the alphabet"); } else if (comparison > 0) { System.out.println(string2 + " comes before " + string1 + " in the alphabet"); } else { System.out.println("The strings are identical"); } RUN Enter a String: Enter another String: goodbye comes before hello in the alphabet hello goodbye

Using some classes written for you

Oblong

Using some classes written for you Oblong EasyScanner

Using some classes written for you Oblong EasyScanner BankAccount

Oblong

public class RectangleCalculations { public static void main(String[ ] args) { double length, height; // code to get length and height System.out.println(“Area = " + area(length,height) ); System.out.println(“Perimeter = " + perimeter(length,height) ); private static double area (double lengthIn, double heightIn) { return lengthIn * heightIn; } private static double area (double lengthIn, double heightIn) { return 2* (lengthIn * heightIn_; }

public class RectangleCalculations { public static void main(String[ ] args) { double length, height; // code to get length and height System.out.println(“Area = " + area(length,height) ); System.out.println(“Perimeter = " + perimeter(length,height) ); } private static double area (double lengthIn, double heightIn) { return lengthIn * heightIn; } private static double area (double lengthIn, double heightIn) { return 2* (lengthIn + heightIn); }

Methods of the Oblong class..

Oblong Oblong myOblong = new Oblong(12.5, 20);

setLength myOblong.setlength(17.5);

setHeight myOblong.setHeight(12);

getHeight System.out.println( ); myOblong.getHeight( )

getLength System.out.println( ); myOblong.getLength( )

calculateArea System.out.println( ); myOblong.calculateArea( )

calculatePerimeter System.out.println( ); myOblong.calculatePerimeter( )

Issues with using the Scanner class for keyboard input….

it is necessary to create a new Scanner object in every method that uses the Scanner class; there is no simple method such as nextChar for getting a single character like there is for the int and double types; the next method doesn't allow us to enter strings containing spaces.

The EasyScanner class resolves these problems!

The input methods of the EasyScanner class Java typeEasyScanner method intnextInt() doublenextDouble() charnextChar() StringnextString()

To use the methods of EasyScanner we do not need to create an object!

char c; System.out.print("Enter a character: "); c = EasyScanner.nextChar(); String s; System.out.print("Enter a string: "); s = EasyScanner.nextString();

The BankAccount class ….

The BankAcount class contains methods to process a bank account. BankAccount Susan Richards Sumana Khan 150.0

The methods of the BankAccount class MethodDescriptionInputsOutput BankAccount A constructor. It accepts two strings and assigns them to the account number and account name respectively. It also sets the account balance to zero. Two String objects Not applicable getAccountNumber Returns the account number.NoneAn item of type String getAccountName Returns the account name.NoneAn item of type String getBalance Returns the balance.NoneAn item of type double deposit Accepts an item of type double and adds it to the balance An item of type double None withdraw Accepts an item of type double and subtracts it from the balance An item of type double None

public class BankAccountTester { public static void main(String[ ] args) { BankAccount account1 = new BankAccount(" ","Susan Richards"); account1.deposit(1000); System.out.println("Account number: " + account1.getAccountNumber()); System.out.println("Account name: " + account1.getAccountName()); System.out.println("Current balance: " + account1.getBalance()); } }

Account number: Account name: Susan Richards Current balance:

Arrays of objects..

int[] someArray = new int[3]; An array of 3 integers An array of 3 BankAccount objects BankAccount[] accountList= new BankAccount[3];

The effect on memory of creating an array of objects …

null accountList accountList = new BankAccount [3]; reference to bank account Java instructionComputer memory BankAccount[] accountList; null

Adding bank accounts to the array …

accountList[0] = new BankAccount(" ","Susan Richards"); accountList[1] = new BankAccount(" ","Delroy Jacobs"); accountList[2] = new BankAccount(" ","Sumana Khan");

accountList[1] BankAccount with account number " " and name "Sumana Khan" accountList[2] accountList[0] BankAccount with account number " " and name "Susan Richards" BankAccount with account number " " and name "Delroy Jacobs" accountList

Accessing objects in an array ….

accountList[0].deposit(1000); returns a BankAccount object calls a BankAccount method accountList[0].withdraw(500); accountList[2].deposit(150);

public class BankAccountTester2 { public static void main(String[ ] args) { BankAccount[ ] accountList = new BankAccount[3]; accountList[0] = new BankAccount(" ","Susan Richards"); accountList[1] = new BankAccount(" ","Delroy Jacobs"); accountList[2] = new BankAccount(" ","Sumana Khan"); accountList[0].deposit(1000); accountList[2].deposit(150); accountList[0].withdraw(500); for(BankAccount item : accountList) { System.out.println("Account number: " + item.getAccountNumber()); System.out.println("Account name: " + item.getAccountName()); System.out.println("Current balance: " + item.getBalance()); System.out.println(); } } }

Account number: Account name: Susan Richards Current balance: Account number: Account name: Delroy Jacobs Current balance: 0.0 Account number: Account name: Sumana Khan Current balance: 150.0

Practical Work

Follow these steps to make use of classes written for you (such as Oblong and EasyScanner)..

First, go to this module’s web site and download the classes we have written for you..

Now, every time your program needs to use a file (such as Oblong), add it to your project!

This program needs access to the Oblong class

Right click your project (or choose Project from the menu)

Choose Add >Add Exisiting Files

Select the file(s) you need.

You will be asked if you want this file to be added into your project or kept outside.

Select Add to add the file into your project.

File has been added and your program will now compile!

Remember the programs you write should not have the same name as our files!

public class TestOblong { public static void main (String[ ] args) { Oblong ob1 = new Oblong (4.2, 10); System.out.println("area = " + ob1.calculateArea()); System.out.println("permeter = " + ob1.calculatePerimeter()); }

public class TestOblong { public static void main (String[ ] args) { Oblong ob1 = new Oblong (4.2, 10); System.out.println("area = " + ob1.calculateArea()); System.out.println("permeter = " + ob1.calculatePerimeter()); }

public class TestOblong { public static void main (String[ ] args) { Oblong ob1 = new Oblong (4.2, 10); System.out.println("area = " + ob1.calculateArea()); System.out.println("permeter = " + ob1.calculatePerimeter()); }

public class TestOblong { public static void main (String[ ] args) { Oblong ob1 = new Oblong (4.2, 10); System.out.println("area = " + ob1.calculateArea()); System.out.println("permeter = " + ob1.calculatePerimeter()); } area = 42.0

public class TestOblong { public static void main (String[ ] args) { Oblong ob1 = new Oblong (4.2, 10); System.out.println("area = " + ob1.calculateArea()); System.out.println("perimeter = " + ob1.calculatePerimiter()); }

public class TestOblong { public static void main (String[ ] args) { Oblong ob1 = new Oblong (4.2, 10); System.out.println("area = " + ob1.calculateArea()); System.out.println("perimeter = " + ob1.calculatePerimiter()); } area = 42.0 perimeter = 28.4

Design and implement a program that performs in the following way: when the program starts two bank accounts are created, using names and numbers which are written into the code; the user is then asked to enter an account number, followed by an amount to deposit in that account; the balance of the appropriate account is then updated accordingly – or if an incorrect account number was entered a message to this effect is displayed; the user is then asked if he or she wishes to make more deposits; if the user answers 'y' (for yes), the process continues; if the user answers 'n' (for no), then both account details (account number, account name and balance) are displayed.

***Bank Program*** Which bank account?:

***Bank Program*** Which bank account?: a123

***Bank Program*** Which bank account?: a123 How much to deposit?

***Bank Program*** Which bank account?: a123 How much to deposit? 250

***Bank Program*** Which bank account?: a123 How much to deposit?250 More deposits?

***Bank Program*** Which bank account?: a123 How much to deposit?250 More deposits? n

***Bank Program*** Which bank account?: a123 How much to deposit?250 More deposits?n number: a123 name: Aaron balance: number: a456 name: Obama balance: 0.0