SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: (from 6.00 - 7.20) Ms Mihaela Cocea Room 103.2 London Knowledge Lab 23-29 Emerald.

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.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
Understanding class definitions Looking inside classes 3.0.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Understanding class definitions Looking inside classes.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
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;
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
LAB 10.
Computer Programming Lab(5).
Warm-Up: Monday, March 3 List all devices you can think of that can be used to input information into the computer.
Conditionals (Cont’d). 2 Nested if/else question Formula for body mass index (BMI): Write a program that produces output like the following: This program.
Methods and You. Up to this point, I have covered many different data types with you. Variables can be considered the nouns of an English sentence. If.
CSC172 Intro Pepper. Goals Reminder of what a class is How to create and use classes How to design classes How to think in terms of objects How to comment.
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.
1 Fencepost loops “How do you build a fence?”. 2 The fencepost problem Problem: Write a class named PrintNumbers that reads in an integer called max and.
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.
SOFTWARE AND PROGRAMMING 1 Lecture 2, 2011 Instructor: Prof. Boris Mirkin DCSIS, room 744, tel Labs: from 26/1,
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: Ms Mihaela Cocea (from ) Room London Knowledge Lab Emerald.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
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 on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Java Arrays and Methods MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh.
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
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.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Cumulative algorithms. 2 Adding many numbers How would you find the sum of all integers from ? // This may require a lot of typing int sum = 1 +
Building Java Programs Program Logic and Indefinite Loops.
Martin T. Press.  Main Method and Class Name  Printing To Screen  Scanner.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
SOFTWARE AND PROGRAMMING 1 Lecture 4: Ticketing machine details: Constructor, method, static/instance variables Instructor: Prof. Boris Mirkin
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
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.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
SOFTWARE AND PROGRAMMING 1 Lecture 2, 2010 Labs start : DCSIS room 131 LAB SH room B29 Lecture EACH student must have obtained.
Building Java Programs Chapter 4 Lecture 4-1: Scanner ; cumulative algorithms reading: 3.3 – 3.4, 4.2.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
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.
SOFTWARE AND PROGRAMMING 1
Building Java Programs
Exercise 1- I/O Write a Java program to input a value for mile and convert it to kilogram. 1 mile = 1.6 kg. import java.util.Scanner; public class MileToKg.
Suppose we want to print out the word MISSISSIPPI in big letters.
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 5: Control Structures II
SELECTION STATEMENTS (1)
Something about Java Introduction to Problem Solving and Programming 1.
Building Java Programs
Control Statement Examples
Building Java Programs Chapter 4
The for-loop and Nested loops
Building Java Programs
Building Java Programs
Chapter 7: User-Defined Functions II
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Random Numbers while loop
Building Java Programs
Building Java Programs
Presentation transcript:

SOFTWARE AND PROGRAMMING 1 In-class open-book TEST1 on 6/02 Lab SH131: (from ) Ms Mihaela Cocea Room London Knowledge Lab Emerald Street Tel.:

2 Test1 6/2/8 awareness Open-book in-class Test1 6/2/8 subjects: Variable: type, declaration, initialisation Expression Loop for Loop while if( )… else if( )... else Method

3 Contents Ticket Machine with a menu and main method Working over a menu: –while and –if/else if/else Using TextIO/Scanner for input Constructor Static and instance variables

4 Ticket Machine Imitates issuing flat-rate tickets Three variables needed: price – for ticket price balance – for the user’s money total – for money received from customers Three assessor methods for getting each of the variables Three mutator methods for - entering customer’s money - printing/issuing a ticket - getting refunded

5 Blue-J Ticket Machine: a review Shortcomings: No main method – cannot be used in JDK Input only with BlueJ capabilities, not with JDK Methods not ordered – refund may occur before a ticket has been issued - can be addressed by organising a dialog or menu

6 Organising a menu //--- ‘menu’ method for choosing action public static int menu() { TextIO.putln(); TextIO.putln("Please enter a number: "); TextIO.putln(" 0 - to quit "); TextIO.putln(" 1 - to get a ticket price "); TextIO.putln(" 2 - to put money and get a ticket "); TextIO.putln(" 3 - to get refunded "); TextIO.putln(" 4 - to get statistics "); int action=TextIO.getInt(); return action; }

7 Main method using menu: right? public static void main(String[ ] args){ int MeItem=1; while (MeItem!=0){ MeItem=menu();// a method if (MeItem==1){ int pp=getPrice(); // a method System.out.println("The ticket price is "+pp+" pence ");} else if (MeItem==2) { System.out.println("Please key in the money inserted, in pence"); int money.insert=TextIO.getInt(); insertMoney(money_insert); printTicket();} else if (MeItem==3) { int refund=refundBalance(); System.out.println("Please take your refund " + refund);} else {int tt=getTotal(); int bb=getBalance(); System.out.println("The total for tickets: "+tt);} }//end of while for choosing action } //end of main

8 Main method using menu: WRONG! WHY? There are some deficiencies in the program: no difference between option 4 and !(1 | 2 | 3) – but this wouldn’t make the class fail Because main method is static, but other methods and variables are not A Java Commandment : You shalt not utilise non static items in a static method! What to do? Either –Make other methods and variables static too; this works but may be in odds with flexibility considerations –Introduce an instance of the class into main method – make the constructor working – and use all methods and variables from the instance

9 Main method using menu: Right (I) public static void main(String[ ] args){ System.out.println("Please enter a ticket price "); int pi=TextIO.getInt(); TM atm=new TM(pi); int MeItem=1; while (MeItem!=0){ MeItem=menu();// a method if (MeItem==1){ int pp=atm.getPrice(); // a method System.out.println("Ticket price is "+pp);}

10 Main method using menu: Right (II) else if (MeItem==2) { System.out.println(“Key in the money inserted in pence"); int money_insert=TextIO.getInt(); atm.insertMoney(money_insert); atm.printTicket();} else if (MeItem==3) { int refund=atm.refundBalance(); System.out.println("Please take your refund " + refund);} else {int tt=atm.getTotal(); int bb=atm.getBalance(); System.out.println("The total for tickets: "+tt);} }//end of loop while for choosing action } //end of main

11 Loop for : reminder I General form: for(CounterInit; Test; CounterUpdate) { } Three parts: for – name of the loop ( ) – control of the loop { } – computations at each loop’s iteration Needs to be remembered: Process of computation is controlled in ( ) – it is only from here an exit from the loop is possible (at Test=False) Computations are performed in { }; when finished, the process goes back to ( )

12 Loop for : reminder II Task: Print integers from 0 to 10 in one line for(int ii=0; ii<=10; ii++) {System.out.print(ii + “ ”); } If one wants change the number 10 to 15? for(int ii=0; ii<=15; ii++) {System.out.print(ii + “ ”); } Or, more flexible, int lim =15; for(int ii=0; ii<=lim; ii++) {System.out.print(ii + “ ”); }

13 Loop for : reminder III Or, even more flexible, with a method int printint(int lim){ for(int ii=0; ii<=lim; ii++) {System.out.print(ii + “ ”); } } //end of method printint printint(15); //calling method at lim=15 Q: Can you find anything wrong in the method printint ? (A: (i) int output type, (ii) should put System.out.println(); in the end) Q: How to modify this if I want … printed? (A: Think, or if you don’t want to, use filtering condition ii%5==0 )

14 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 or double ) from keyboard

15 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 classend Two errors in this code: in lines 1 and 3. Please guess! Answer: no ; and non-static num

16 Using a method with Scanner import java.util.* class PrintMDot{ public static void main(String[ ] args){ Scanner scap = new Scanner(System.in); System.out.println(“How many ampersands to print? “); int number=scap.nextInt(); ppp(number); } //end of main static void ppp(int nnn) { for (ik=0; ik<nnn; ik++) System.out.print(‘&’); System.out.println(); } //end of ppp } //end of class - some errors are here too! Try to find

17 Constructor Constructor is a special method that –Has the same name as the class –No return type (nor “return”) –Is called with modifier “new” to reserve a memory space for an object of class type (an instance) List of parameters, as well as the block, can be user defined The constructor with no parameters is available by default (like Const(){ }; )

18 Static and instance variables Static variable:belongs to its class, and it is shared by all class instances, with the same value Instance variable:a class variable without the “static” modifier, is shared by all class instances, but its values can differ in different instances Local variable: is created within a method or instance in a { } block. Its scope is limited within the block.

19 Example (1) public class TesNum { int instVar = 1; static int statVar = 10; TesNum() { System.out.println("test: " + instVar + " and " + statVar); instVar = 7; statVar = 5; } \\ constructor

20 Example(2) public static void main(String[] args) { TesNum alpha1 = new TesNum(); alpha1.instVar = 3; alpha1.statVar = 6; //syn. to: TesNum.statVar = 6; TesNum alpha2 = new TesNum(); System.out.println("inst: " + alpha1.instVar + " and " + alpha2.instVar); System.out.println("stat: " + alpha1.statVar + " and " + alpha2.statVar); //System.out.print("mix: " + instVar + " and " + statVar); wrong } //end of main } //end of class

21 What’s going on in TesNum instVar statVar 1. With the class: 1 (in class) At the constructo r in class (virtual): After alpha1 :Constructor prints:1 and 10 3 (within alpha1)6 4. After alpha2 :Constructorprints:1 and6 7 (within alpha2)5 5. Method main prints:3 and 7 5 and 5

22 A method added: public int SS(int a){ int b=instVar; int sum=0; if (a>b){ //swap a and b int c=b; b=a; a=c;} for(int i=a;i<=b;i++) sum=sum+i; return sum; } // computes the sum of integers from a to b int b1=alpha1.SS(statVar); int b2=alpha2.SS(statVar); System.out.println("sum : " + b1 + " and " + b2);

23 Sums to be printed From alpha1: a=5, b=3 The sum: 3+4+5=12, that is, b1=12 From alpha2: a=5, b=7 The sum: 5+6+7=18, that is, b2=18 The print: sum: 12 and 18

24 References to object variables and methods Examples from TesNum alpha1.statVar alpha2.instVar TesNum.statVar from TesNMod alpha1.SS(statVar)