Intro to Programming & Algorithm Design

Slides:



Advertisements
Similar presentations
Introduction to arrays
Advertisements

CSCI 6962: Server-side Design and Programming Input Validation and Error Handling.
Constants A constant is a variable whose value is expected to remain the same throughout a program It is considered “good programming style” to use constants.
1 Intro to Programming & Algorithm Design Functions Copyright 2003 by Janson Industries This presentation can be viewed on line in a file named: ch06.IntrotoProg.Functions.ppt.
Objectives In this chapter, you will learn about:
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
8 November Forms and JavaScript. Types of Inputs Radio Buttons (select one of a list) Checkbox (select as many as wanted) Text inputs (user types text)
Computer Science 1620 Programming & Problem Solving.
Chapter 4 Making Decisions
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
What is RobotC?!?! Team 2425 Hydra. Overview What is RobotC What is RobotC used for What you need to program a robot How a robot program works Framework.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
General Programming Introduction to Computing Science and Programming I.
07/10/ Strings ASCII& Processing Strings with the Functions - Locate (Instr), Mid, Length (Len), Char (ChrW) & ASCII (Asc)
Copyright © 2002 W. A. Tucker1 Chapter 7 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Mastering Char to ASCII AND DOING MORE RELATED STRING MANIPULATION Why VB.Net ?  The Language resembles Pseudocode - good for teaching and learning fundamentals.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
5-1 Chapter 5 The Repetition Process in VB.NET. 5-2 Learning Objectives Understand the importance of the repetition process in programming. Describe the.
Lecture 2: Classes and Objects, using Scanner and String.
School of Computer Science & Information Technology G6DICP - Lecture 9 Software Development Techniques.
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
Math class services (functions) Primitive vs reference data types Scanner class Math class services (functions) Primitive vs reference data types Scanner.
Intro to Programming & Algorithm Design
C++ Programming Language Lecture 2 Problem Analysis and Solution Representation By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
30/10/ Iteration Loops Do While (condition is true) … Loop.
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
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.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
1 Intro to Programming & Algorithm Design Arrays Copyright 2003 by Janson Industries This presentation can be viewed on line in a file named: ch08.IntrotoProg.Arrays.ppt.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
The Hashemite University Computer Engineering Department
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
COP 2551 Introduction to Object Oriented Programming with Java Topics –Introduction to the Java language –Code Commenting –Java Program Structure –Identifiers.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
Session Three Review & Conditional Control Flow. Java File Hierarchy Projects Packages Classes Methods.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Agenda Warmup Lesson 1.4 (double precision, String methods, etc)
CS161 Introduction to Computer Science
Testing and Debugging.
Conditions and Ifs BIS1523 – Lecture 8.
Fundamental Error Handling
We’re moving on to more recap from other programming languages
4.1 Strings ASCII & Processing Strings with the Functions
Coding Concepts (Data- Types)
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Chapter 7: Input Validation
Chapter 3: Selection Structures: Making Decisions
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Math class services (functions)
Presentation transcript:

Intro to Programming & Algorithm Design 4/17/2017 Intro to Programming & Algorithm Design Input Validation Assg This presentation can be viewed on line in a file named: ch07.IntrotoProg.InputValidation.ppt Copyright 2003 by Janson Industries

Objectives Explain Show how to code validation functions in Java 4/17/2017 Objectives Explain GIGO (garbage in garbage out) Defensive programming The input validation loop Different types of validation Data type Range Completeness Show how to code validation functions in Java

4/17/2017 GIGO The program can be coded correctly but if you put bad data in, you will get bad results This has been the demise a many a new application All coding done and correct but the data conversion wasn't done properly I.e. the customer db data is incorrect so all the bills are sent to the wrong customers

GIGO Not just true of programs 4/17/2017 GIGO Not just true of programs What happens if you put diesel in your car engine? You had a perfectly good car but then ruined it with bad input That’s why car manufacturers build the car so only the unleaded nozzle fits That's a form of input validation!

Defensive Programming 4/17/2017 Only provide valid values that the user can select from The ubiquitous state abbr list Checkboxes/buttons indicating selected values I accept the license agreement Write code to detect all possible data errors and then either Correct the error Inform the user of the error and provide info to help them correct it

Data Errors Wrong type of data Completeness/invalid size 4/17/2017 Wrong type of data Numbers vs. text For month: "November" vs. 11 Integers vs. decimal numbers For month: is 11.53 a valid month Completeness/invalid size Did the user enter no data or only part of the data 3224 for a zip code Put in too much data 322456245374835374 for a zip code

Data Errors Data not within a valid range 4/17/2017 Data not within a valid range Month should be between 1 and 12 Birthdates should not be over 120 yrs ago Data not from valid set of values Gender can be "M" or "F" Data integrity Zip code entered not valid for state abbr entered Customer number entered not valid

Data Validation Pre-test Loop 4/17/2017 Data Validation Pre-test Loop Standard way of making sure data is valid Prompt user for data Read the data in Have a loop that tests the data validity If not valid Fix data or display a useful message so the user can fix the data Read the data again

Data Validation Pre-test Loop 4/17/2017 Data Validation Pre-test Loop Function String getMonth() Declare String month Declare Integer monthNumber // User prompt explains the valid values Display "Enter a month number between 1 and 12" Input month monthNumber = stringToInteger(month) While (monthNumber < 1 OR monthNumber > 12) Display "Enter a month number. For example, 1 for Jan, 2 for Feb" End While Return month End Function

Data Validation Pre-test Loop 4/17/2017 Data Validation Pre-test Loop getMonth() Declare String month Integer monthNumber Display “Enter a month number between 1 and 12” Input month monthNumber= stringToInteger(month)

While monthNumber<1 OR monthNumber >12 4/17/2017 False While monthNumber<1 OR monthNumber >12 True Display “Enter a month number. For example, 1 for Jan, 2 for Feb" Input month monthNumber= stringToInteger(month) Return month

Data Validation Loop How could we have fixed the data for the user? 4/17/2017 Data Validation Loop How could we have fixed the data for the user? Check to see if the three character abbr or full text for the month was entered If so, change to the correct number Check to see if a space(s) was entered at the beginning or end of the text If so, trim the space(s) off

Data Validation Post-test Loop 4/17/2017 Data Validation Post-test Loop Start loop Prompt the user for the data Read the data in End of loop validity test, if not valid, go to the start of the loop A lot less code but only one prompt/msg to the user No useful error msg with further info

Data Validation Post-test Loop 4/17/2017 Data Validation Post-test Loop Function String getMonth() Declare String month Declare Integer monthNumber Do // User prompt explains the valid values Display "Enter a month number between 1 and 12" Input month monthNumber = stringToInteger(month) While (monthNumber < 1 OR monthNumber > 12) Return month End Function

Data Validation Post-test Loop 4/17/2017 Data Validation Post-test Loop

4/17/2017 Validation Functions For data that is commonly input, create validation functions that many programs can use Many programs may ask for the month Have a common function to get data and do all the validation Advantage: only written once Less coding If need to change, change in only one place

4/17/2017 MyUtils

4/17/2017 MyUtils Any program that requests a date can now use the day and month functions public class Test { public static void main(String[] args) { String month = null, day = null; int monthNumber = 0; month = MyUtils.getMonth(); monthNumber = Integer.valueOf(month); day = MyUtils.getDay(monthNumber); MyUtils.p("The date entered is " + month + "/" + day); }

Validating Strings Added problem of lower and upper case 4/17/2017 Validating Strings Added problem of lower and upper case "yes", "YES", "Yes", "yEs" are all different values Easiest solution is to change input to either upper or lower case then test for the value

4/17/2017 Validating Strings Restaurant is asking customer for items they want (pizza, soda, calzone, etc.) and sizes Need to validate both the item and size Since the sizes (small, medium, and large) are the same for all items will create a common getSize function

4/17/2017 Validating Strings getSize will also check to see if the user enters "s", "m", or "l" If so will convert to "small", "medium" or "large" In case of a typo ("meduim", "larj", "smal", etc.) will check the first letter if "s", "m", or "l", will convert to "small", "medium" or "large"

String Validation main() Declare String item, size; 4/17/2017 String Validation main() Declare String item, size; Display "Enter the item you want to purchase: Pizza, Calzone or Soda" Input item item = toLower(item) While (item != "pizza" AND item != "calzone" AND item != "soda") Display "Please enter Pizza, Calzone or Soda " End While size = getSize(item) Display "You have ordered a ", size, " ", item End

String Validation Function String getSize(String item) 4/17/2017 String Validation Function String getSize(String item) Declare String size // User prompt asks for size Display "Enter the size ", item, " you would like" Input size size = toLower(size) While (size != "small" AND size != "medium" AND size != "large")

String Validation If (substr(size, 0 , 1) = "s" OR substr(size, 0, 1) 4/17/2017 If (substr(size, 0 , 1) = "s" OR substr(size, 0, 1) = "m" OR substr(size, 0, 1) = "l" Then If substr(size, 0 , 1) = "s" Then size = "small" Else If substr(size, 0 , 1) = "m" Then size = "medium" Else size = "large" End If Display "Enter small, medium, or large" Input size size = toLower(size) End While Return size End Function String Validation

4/17/2017 Flow Chart - SFC

4/17/2017 Flow Chart - SFC Flow Chart - SFC

4/17/2017 Flow Chart - SFC

Flow Chart - SFC 4/17/2017

4/17/2017 Flow Chart - Raptor Raptor cannot convert strings to upper or lower case However, we can write a function to do it All characters can be represented as numbers In ASCII, A-Z are 65-90 and a-z are 97-122

ASCII Chart

Flow Chart - Raptor 4/17/2017 Raptor can return the number associated with a particular character or visa versa charNum = to_ascii('A') charNum will equal 65 char = to_character(97) char will equal 'a' You can manipulate a character value as if it were a number Add 32 to get lower case character

Flow Chart - Raptor Raptor cannot perform a true substring function 4/17/2017 Flow Chart - Raptor Raptor cannot perform a true substring function Can identify a single character within a string by specifying the index of the character Assuming address = "1 Main St" address[3] is "M" address[7] is " "

4/17/2017 Flow Chart - Raptor When an index is used, value type is character NOT string Comparing two different value types can't be done 123 = "123" is invalid Or in this case address[3] = "M" is invalid However, address[3] = 77 is valid Could also create a character variable with the value "M" charVar = to_character[77]

toLowerCase Function String toLowerCase(String stringToChange) 4/17/2017 toLowerCase Function String toLowerCase(String stringToChange) Declare Integer ctr = 1 While ctr <= length(stringToChange) If stringToChange[ctr] > 64 AND stringToChange[ctr] < 91 stringToChange[ctr] = stringToChange[ctr] + 32 End If ctr = ctr + 1 End While Return stringToChange End Function

Raptor toLowerCase() Had to change loop condition because of Raptor 4/17/2017 Had to change loop condition because of Raptor Notice how character value treated like a number

4/17/2017 Raptor main() Notice stringToChange retrieved, toLowerCase invoked, then we have to place stringToChange value into item.

4/17/2017

4/17/2017 Raptor getSize()

Again, notice how character value treated like a number 4/17/2017 Raptor getSize() Again, notice how character value treated like a number

4/17/2017 When GetItem run

Prompted for valid item 4/17/2017 PIAZZ changed to piazz Prompted for valid item

Pizza changed to pizza Prompted for a size 4/17/2017 Pizza changed to pizza Prompted for a size

LARJ changed to larj and size set to large 4/17/2017 LARJ changed to larj and size set to large Message displayed

Java Does have a toLowerCase method 4/17/2017 Java Does have a toLowerCase method So we don't have to mathematically manipulate the ASCII integer values Also has an equalsIgnoreCase method String name = "MOE"; name.equalsIgnoreCase("moe"); Is true

Negative logic (!) in while 4/17/2017 Java GetItem Uses toLowerCase Negative logic (!) in while

Uses the substring function Java getSize 4/17/2017 Uses the substring function

Bad values caught and corrected 4/17/2017 Java GetItem Bad values caught and corrected

Reading Mixed Data 4/17/2017 Java lets you read individual values not just the whole line next() gets all text on a line up to the next space nextInt() gets all text up to the next space and converts it to an integer nextDouble() gets all text up to the next space and converts it to a double None of these advance the cursor to the next line!

Processing Data Not nitpicking! If entered the following budget data 4/17/2017 Not nitpicking! If entered the following budget data And you tried to process with these statements Rent 500 Car 280 item1 = keyboard.nextLine(); item1Amount = keyboard.nextInt(); item2 = keyboard.nextLine(); item2Amount = keyboard.nextInt();

Processing Data 4/17/2017 There would be an InputMismatchException the second time nextInt executed WHAAAAAAAT!! Must show where cursor is after each statement executed to understand First nextLine() reads "Rent" and places cursor at the beginning of the second line

Cursor after first read Cursor after second read Processing Data 4/17/2017 When nextInt executed 500 read and cursor placed at end after the second 0 When the second nextLine (3rd read) executed, it reads the rest of the second line A big fat null Rent 500 Car 280 Cursor after first read Cursor after second read

Processing Data And cursor placed at beginning of third line 4/17/2017 And cursor placed at beginning of third line Now when second nextInt executed InputMismatchException Tries to convert "Car" into a int Rent 500 Car 280 Cursor after 3rd read (2nd nextLine)

Processing Data Solution: Execute another nextLine after the nextInt 4/17/2017 Processing Data Solution: Execute another nextLine after the nextInt Forces the cursor to the line after the line with the int value item1 = keyboard.nextLine(); item1Amount = keyboard.nextInt(); keyboard.nextLine(); item2 = keyboard.nextLine(); item2Amount = keyboard.nextInt();

4/17/2017 Points to Remember Bad input will make an application yield incorrect results Defensive programming consists of many techniques used to stop bad input All character data can be represented as an integer value

Assignments Non-Graded Graded Chap 7 labs 7.1-7.4 4/17/2017 Assignments Non-Graded Chap 7 labs 7.1-7.4 The Word doc is very large, you must delete the video links or the email will be blocked Graded Chap 7 lab 7.5