Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

Similar documents
Exercise 4: Loops, Arrays and Files

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Lesson 3: Accepting User Input and Using Different Methods for Output

Lecture Notes: ESC 101

UEE1302(1102) F10: Introduction to Computers and Programming

CSEN 202 Introduction to Computer Programming

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

CMIS 102 Hands-On Lab

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Lecture 4. A Real Java Program!! Generic Program Template. You first Java programs. Program design guidelines. Examples.

Conditional Programming

Case Study: Savings Account Interest

Software Practice 1 Basic Grammar

ECSE 321 Assignment 2

Lecture 10: Boolean Expressions

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

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

CS Programming I: Arrays

Input & Output in Java. Standard I/O Exception Handling

Topics. Chapter 5. Equality Operators

Lecture 11. Example 1. Introduction. Method definition and invocation. Parameter passing: value vs. reference parameters. Scope and Lifetime.

1. Download the JDK 6, from

Recitation: Loop Jul 7, 2008

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Syntax and Variables

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

Flow of Control Branching 2. Cheng, Wei COMP May 19, Title

CONDITIONAL EXECUTION

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CSEN 202 Introduction to Computer Programming

Building Java Programs

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

COMP 202 Java in one week

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Building Java Programs

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Do this by creating on the m: drive (Accessed via start menu link Computer [The m: drive has your login id as name]) the subdirectory CI101.

Example: Monte Carlo Simulation 1

Algorithms and Problem Solving

FREQUENTLY ASKED QUESTIONS

Simple Java Reference

i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture

Building Java Programs

Section 1.2: What is a Function? y = 4x

CS 112 Introduction to Programming

CS 112 Introduction to Programming

(b) This is a valid identifier in Java: _T_R-U_E_. (c) This is a valid identifier in Java: _F_A_L_$_E_

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSE 142, Summer 2014

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Loops. CSE 114, Computer Science 1 Stony Brook University

Learning the Java Language. 2.1 Object-Oriented Programming

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples

2.8. Decision Making: Equality and Relational Operators

Midterms Save the Dates!

JAVA OPERATORS GENERAL

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Algorithms and Conditionals

Data Types and the while Statement

A sample print out is: is is -11 key entered was: w

This report is based on sampled data. Jun 1 Jul 6 Aug 10 Sep 14 Oct 19 Nov 23 Dec 28 Feb 1 Mar 8 Apr 12 May 17 Ju

Course Outline. Introduction to java

Programming Basics. Digital Urban Visualization. People as Flows. ia

Lecture 11.1 I/O Streams

Byte and Character Streams. Reading and Writing Console input and output

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

CMSC 331 Second Midterm Exam

Java Programming Language Mr.Rungrote Phonkam

2

Lecture Set 2: Starting Java

Introduction to Programming Using Java (98-388)

Program Elements -- Introduction

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

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Loops (while and for)

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Lecture Set 2: Starting Java

Claremont McKenna College Computer Science

CSE 142, Summer 2015

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Chapter 3. Selections

Classes Basic Overview

13 th Windsor Regional Secondary School Computer Programming Competition

Chapter 4 Introduction to Control Statements

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

Questions? Static Semantics. Static Semantics. Static Semantics. Next week on Wednesday (5 th of October) no

All King County Summary Report

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CS 112 Introduction to Programming

CSE 341 Section Handout #6 Cheat Sheet

CSc 2010 Principles of Computer Science, Fall 2013 Practice Problems for Midterm 3* * 3 17 % 9-20 % (26 / 7) "2"

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Topic 4 Expressions and variables

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Transcription:

// Simple program to show how an if- statement works. import java.io.*; Lecture 6 class If { static BufferedReader keyboard = new BufferedReader ( new InputStreamReader( System.in)); public static void main (String[] args) throws IOException { int age; Nested if s reprise. // output initial message System.out.print("Please enter your age: "); The boolean data type. More complex selection statements: switch. // input age age = new Integer(keyboard.readLine()).intValue(); Examples. Material from Holmes Chapter 3 (final part). // computation System.out.print("Here is your drink! "); if (age > 17) System.out.println("<whisky>"); System.out.println("<milk>"); 1 2-1 Drinking Last time we saw a simple example of a program involving conditionals. 1. output Please enter your age: ; 2. input age; 3. if (age 17) 4. output Here s your drink! 5. 6. output Here s your drink! whisky milk Nested if The statement that follows the conditional expression or the keyword can also be an if- statement. The resulting instruction is a nested if statement. Example. An automated vending machine gives you a glass of whisky if your age is right and you have the exact money! 2 3

milk milk // Simple program to show how nested if- statements works. import java.io.*; Reuse class If2 { static BufferedReader keyboard = new BufferedReader ( new InputStreamReader( System.in)); What do we need to change here? public static void main (String[] args) throws IOException { int age, money; 1. output Please enter your age: ; 2. input age; 3. if (age 17) 4. output Here s your drink! whisky // output initial message System.out.print("Please enter your age: "); // input age age = new Integer(keyboard.readLine()).intValue(); 5. 6. output Here s your drink! 4 5-1 Pseudocode 1. output Please enter your age: ; 2. input age; 3. if (age 17) 4. if (money 50) 5. output Here s your drink! 6. 7. output a farewell message! 8. 9. if (money 30) 10. output Here s your drink! 11. 12. output a farewell message! whisky // computation if (age > 17) { System.out.print("Please enter the money (50p): "); money = new Integer(keyboard.readLine()).intValue(); if (money == 50) System.out.println("Here is your drink! <whisky>"); System.out.print("Sorry! No drink! You gave me too "); if (money > 50) System.out.println("much money!"); System.out.println("little money!"); { System.out.print("Please enter the money (30p): "); money = new Integer(keyboard.readLine()).intValue(); if (money == 30) System.out.println("Here is your drink! <milk>"); System.out.print("Sorry! No drink! You gave me too "); if (money > 30) System.out.println("much money!"); System.out.println("little money!"); 5 5-2

Remarks Pitfall with nested statements: can you spot the mistake in this example? One loses the first branch. Indentation! But do not over-indent! Boolean Expressions We have looked at relational operators last time. One can do calculations with booleans exactly in the same way as one can do calculations with numbers. - 12 34214 + 51 2367*(-85131)!false false true true && (!false)! is the logical negation, && is the logical conjunction and the logical disjunction.!(4 < a) (a <= 12) (a % 2 == 0) (0 <= a) && (a <= 9) 6 8 Primitive Data Type 4 Type Booleans Values false and true. Keyword boolean. Operators false, true Relational operators (producing a boolean value): <, >, ==,!=, <=, >=. Boolean operators (composing boolean values):!, &&,. Precedence: boolean operators have lower priority than arithmetic and relational ones (but higher than the assignment).. Boolean operators tables A B!A A && B A B true true false true true true false false false true false true true false true false false true false false Boolean expressions are used in the conditions of a selection statement and in loops (next week). 7 9

Switch If a selection is based on the values of some expression, belonging to an ordinal type then a switch statement may be used instead of a nested if-. Syntax. General format of a switch statement. switch ( expression ) case constant-expression : statements case constant-expression : statements... default : statements Exiting from a switch: the last statement executed in each case must be a break statement, otherwise Java would go sequentially to evaluate next condition. Problem Analysis. The validation of the date has a three-part solution. The first part is to validate a month as an integer in the range If the month is treated as an ordinal value of a switch expression, with case labels occurring for each of the twelve months, then should a month not be in the range 1 to 12, the error can be trapped as the default value. The second part involves the calculation of a leap year, and will only be considered if the month happens to be February. This calculation uses the following rules: if the year is evenly divisible by 4 and the year is not a century or the year is a century that is divisible by 400 then the year is a leap year! The third part of the solution involves the calculation of the number of days in a month.. 10 12 Algorithm. Case Study: Validation of Dates including Leap Years Problem. We want to write a program that validates a date. The format of the date MMDDYYYY is a single integer representing month, day and year. The single integer is split into individual integers representing MM, DD and YYYY. The program checks that the number of months in a year should not exceed 12, and that the number of days in each month has not been exceeded. The program also reports on leap years. 1. input the date 2. split the date into month, day and year?? 3. calculate the number of days in the month 1, 3, 5, 7, 8, 10, 12 numberofdays = 31; 4, 6, 9, 11 numberofdays = 30; 2 if it is a leap year then numberofdays = 29; numberofdays = 28; 4. output results (reporting errors...) 11 13

// chap_3\ex_9.java // program to validate a date in the format MMDDYYYY import java.io.*; class Ex_9 { static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); public static void main(string[] args) throws IOException { int date; int month, day, year; int numberofdays = 0; boolean error = false; // output results if (month == 2 && numberofdays == 29) System.out.println(year + " is a Leap Year"); if (day > numberofdays error) System.out.println("DATA ERROR - check day or month"); System.out.println("Date checked and is valid"); // input date in format MMDDYYYY System.out.println("Input a date in the format MMDDYYYY"); date = new Integer(keyboard.readLine()).intValue(); // split up date into MM DD and YYYY month = date / 1000000; day = (date % 1000000) / 10000; year = (date % 10000); 13-1 13-3 // calculate number of days in month switch(month) { // test for Jan, Mar, May, Jul, Aug, Oct, Dec case 1: case 3: case 5: case 7: case 8: case 10: case 12: numberofdays = 31; break; // test for Apr, Jun, Sep, Nov case 4: case 6: case 9: case 11: numberofdays = 30; break; // test for Feb being a Leap Year case 2: if (((year%4 == 0) && (year%100!= 0)) (year%400 == 0)) numberofdays = 29; numberofdays = 28; break; default: error = true; 13-2 Warm-up exercise Determine the output for each of the following when x is 9 and y is 11 and when x is 11 and y is 9. if ( x < 10 ) if ( y > 10 ) System.out.println("*********"); System.out.println("#########"); System.out.println("$$$$$$$$$"); if ( x < 10 ) { if ( y > 10 ) System.out.println("*********"); { System.out.println("#########"); System.out.println("$$$$$$$$$"); 14

!#"$ % &'( +*), -. / Mortgages Problem. A bank asks you to write a program that computes mortgage payments. From an interview with the bank director you learn that mortgages can be for 10, 15, 20 or 25 years only and that interest rates are different depending on the length of the repayment period. There is an (annual) 7.25% interest over 10 years, 8.5% over 15 years, 9.2% over 20 years and a 9.35% over 25 years. The program should let the user enter the number of years, and the loan amount. Then it will compute the monthly payment as follows: Tutorial Code the mortgage repayment calculator. Modify the drink vending machine program so that if the user input more money than needed for a given choice, the machine returns the chosen drink and a number of coins as the appropriate change. Assume that the amount of money entered is always given in pence, and that the vending machine has an infinite amount of one, five, ten, twenty and fifty pence coins. (Hint: use your solution to Holmes exercise 2.30). 15 17 Program Design 0Problem analysis. Studying the nature of the problem. Define input and output. 0Algorithm. (This is the creative step) Invent a way to solve it. 0Data Dictionary. List the data you need. 0Desk Check. Using traces, check the correctness of your program. 0Screen Layout. Decide how the output should look. 0Coding. Type in your program. 0Test results. After successful compilation, check that you get correct results. 16