CS1101: Programming Methodology Recitation 3 – Control Structures.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

1 More on Decisions Overview l The selection Operator l Grouping of Statements l Multiple branches (if else if) l Switch Statement.
More loops Horstmann Ch 7 continued.. The do-loop continue- condition ? loop-body statements next statement false true WHILE-LOOP continue- condition?
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
ARRAYS public class ArrayDemo { public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Introduction to Computer Programming Decisions If/Else Booleans.
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.
1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Looping Yong Choi School of Business CSU, Bakersfield.
1 Memory Model of A Program, Methods Overview l Closer Look at Methods l Memory Model of JVM »Method Area »Heap »Stack l Preview: Parameter Passing.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
COMP 14: I/O and Boolean Expressions May 24, 2000 Nick Vallidis.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Saravanan.G.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
1 Course Lectures Available on line:
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Programming: From the Ground Up
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
CS1101X: Programming Methodology Recitation 3 Control Structures.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Iteration. 2 Java looping  Options while do-while for  Allow programs to control how many times a statement list is executed.
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 4: Control Structures II
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Iteration. Java looping Options –while –do-while –for Allow programs to control how many times a statement list is executed.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
1 Iteration. 2 Java looping  Options while do-while for  Allow programs to control how many times a statement list is executed.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
Defining Your Own Classes II
Introduction to programming in java
Chapter 7 User-Defined Methods.
CS1101: Programming Methodology Recitation 7 – Exceptions
Objects, Classes, Program Constructs
Testing and Exceptions
Chapter 5: Control Structures II
Iteration.
Control Statement Examples
Iteration.
Exception Handling Contents
Exceptions.
Exceptions.
Presentation transcript:

CS1101: Programming Methodology Recitation 3 – Control Structures

2 Checksum Validation Objective: Develop a program that validates a Universal Product Code (UPC) number. A valid UPC is a 12 digit value that meets the criteria: m is the sum of 2 nd, 4 th, 6 th, 8 th, 10 th digits n is the sum of the 1 st, 3 rd, 5 th, 7 th, 9 th, 11 th digits r = 10 – ((m + 3.n) mod 10) Valid UPC number if 12 th digit is equal to r

3 Checksum Validation Example: m = = 13 n = = 21 r = 10 – (( ) mod 10) = 10 – (76 mod 10) = 10 – 6 = 4 Example: m = = 20 n = = 26 r = 10 – (( ) mod 10) = 10 – (98 mod 10) = 10 – 8 = 2

4 Analysis and Design: −Values m, n and r −Input string s and its numeric representation number −With number, the 12 component digits d1, d2 …, d12 can be determined for initializing m, n and r

Analysis and Design: −Prompt user to supply 12 digit number −Extract input and assign to s −Convert s to a numeric representation number. −If number is negative or has more than 12 digits Then report number is not a UPC code Else Assign least significant (12 th ) digit of number to d12 Assign 11 th digit of number to d11 : Assign 1 st digit of number to d1 Compute m = d2+d4+d6+d8+10 Compute n = d1+d3+d5+d7+d9+d11 Compute r = 10 – ((m – 3.n) mod 10) If r = d12 Then report number is a feasible UPC code Else report number is not a UPC code

// Checks whether a user-specified value meets the UPC criteria import java.io.*; public class UPC { // main(): application entry point public static void main(String[] args) throws IOException { final long MAX_POSSIBLE_UPC_CODE = L; // set input stream and get number BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter a 12-digit whole number: "); String s = stdin.readLine(); long number = Long.parseLong(s); max int value is only 10 digits. Use long to represent UPC code

// determine whether number is a possible upc code if ((number MAX_POSSIBLE_UPC_CODE)) { // not a upc code System.out.println(s + " is an invalid UPC code"); } else {// might be a upc code, determine individual digits int d12 = (int) (number % 10);number /= 10; int d11 = (int) (number % 10);number /= 10; int d10 = (int) (number % 10);number /= 10; int d9 = (int) (number % 10);number /= 10; int d8 = (int) (number % 10);number /= 10; int d7 = (int) (number % 10);number /= 10; int d6 = (int) (number % 10);number /= 10; int d5 = (int) (number % 10);number /= 10; int d4 = (int) (number % 10);number /= 10; int d3 = (int) (number % 10);number /= 10; int d2 = (int) (number % 10);number /= 10; int d1 = (int) (number % 10);number /= 10; % - Java modulus operator

// compute sums of first 5 even digits and the odd digits int m = d2 + d4 + d6 + d8 + d10; int n = d1 + d3 + d5 + d7 + d9 + d11; // use UPC formula to determine required value for d12 int r = 10 - ((m + 3*n) % 10); // based on r, can test whether number is a UPC code if (r == d12) { // is a upc code System.out.println(s + " is a feasible UPC code"); } else { // not a upc code System.out.println(s + " is an invalid UPC code"); }

Nested if statements if (testScore >= 70) { if (studentAge < 10) System.out.println (“You did a great job!”); else System.out.println (“You did pass”); //test score >= 70 and age >=10 } else System.out.println (“You did not pass”); //test score < 70 if (testScore >= 70 && studentAge < 10) { System.out.println (“You did a great job!”); } else {//either test score =10 if (testScore >= 70) System.out.println (“You did pass”); else System.out.println (“You did not pass”); } Print three messages depending on test score and student age

Nested if statements if (num1 < 0) { if (num2 < 0) { if (num3 < 0) negativeCount = 3;//all three are negative elsenegativeCount = 2;//num1 and num2 are negative } else { if (num3 < 0) negativeCount = 2;// num1 and num3 are negative else negativeCount = 1;// num1 is negative } else { if (num2 < 0) { if (num3 < 0) negativeCount = 2;// num2 and num3 are negative else negativeCount = 1;// num2 is negative } else { if (num3 < 0) negativeCount = 1;// num3 is negative else negativeCount = 0;// no negative numbers } Input 3 integers and determine how many of them are negative

Nested if statements More elegant version! negativeCount = 0; if (num1 < 0) negativeCount ++; if (num2 < 0) negativeCount ++; if (num3 < 0) negativeCount ++; Input 3 integers and determine how many of them are negative

Rules for if statements 1.Minimize number of nestings 2.Avoid complex boolean expressions. - Make them as simple as possible. - Don’t include many ANDs and ORs. 3.Eliminate unnecessary comparisons. 4.Don’t be satisfied with first correct statement. Always look for improvement 5. Read your code again. Can you follow the statement easily ? If not, try to improve it.

13 Dataset Analysis Objective: Develop a program that finds the min, max, and mean of a dataset of values. Analysis and Design: Methods: 1.public double getMinimum() 2.public double getMaximum() 3.public double getAverage() These methods return double.NaN if dataset is empty

14 Dataset Analysis Analysis and Design: Constructors: 1.public DataSet () – initialize representation of an empty dataset 2.Public DataSet (String s) – initialize dataset with values from file with name s 3. member methods – getSize(), addValue (double x), clear(), load (String s) Instance variables: private int n private double minimumValue private double maximumValue private double xSum

import java.io.*; public class DataSetTester { public static void main(String[] args) throws IOException { DataSet dataset = new DataSet("age.txt"); System.out.println(); System.out.println("Minimum: " + dataset.getMinimum()); System.out.println("Maximum: " + dataset.getMaximum()); System.out.println("Mean: " + dataset.getAverage()); System.out.println("Size: " + dataset.getSize()); System.out.println(); dataset.clear(); dataset.load("stature.txt"); System.out.println("Minimum: " + dataset.getMinimum()); System.out.println("Maximum: " + dataset.getMaximum()); System.out.println("Mean: " + dataset.getAverage()); System.out.println("Size: " + dataset.getSize()); System.out.println(); }

// Data set summary representation import java.io.*; public class DataSet { // instance variables private int n; private double xSum; private double minimumValue; private double maximumValue; // DataSet(): default constructor public DataSet() { clear(); } // DataSet(): specific constructor public DataSet(String s) throws IOException { load(s); }

// clear(): empties the data set public void clear() { n = 0;xSum = 0; minimumValue = Double.NaN; maximumValue = Double.NaN; } // add(): adds the value to the set public void addValue(double x) { xSum += x; ++n; if (n == 1) { minimumValue = maximumValue = x; } else if (x < minimumValue) { minimumValue = x; } else if (x > maximumValue) { maximumValue = x; }

// load(): adds the values from the file to set public void load(String s) throws IOException { // get a reader for the file BufferedReader fileIn = new BufferedReader( new FileReader(s)); // add values one by one String currentLine = fileIn.readLine(); while (currentLine != null) { double x = Double.parseDouble(currentLine); addValue(x); currentLine = fileIn.readLine(); } // close up file fileIn.close(); }

// getAverage(): compute data set average public double getAverage() { if (n == 0) return Double.NaN; else return xSum / n; } // getMinimum(): produce minimum data set value public double getMinimum() { return minimumValue; } // maximum(): produce maximum data set value public double getMaximum() { return maximumValue; } // getSize(): produce data set size public int getSize() { return n; }