ecology labfaculty.cse.tamu.edu/slupoli/notes/java/validationnotes.docx · web viewdata entered...

29
Validation ( add http://code-defenders.org/help ) Why do we validate?? remember users are stupid, trust me data entered into a database, sucks if you have to run back to the user to fix their error!! no “unsigned” (as of 10/10) o unsigned means positive range (shifts range right) o unsigned byte would be 0 to 255 Some research should go into what value your variable could possibly be o ex: IQ values can be from 0 (brain dead) to over 140 http://www.write-technical.com/126581/session2/ session2.htm 1

Upload: others

Post on 10-Sep-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Validation( add http://code-defenders.org/help)

Why do we validate?? remember users are stupid, trust me data entered into a database, sucks if you have to run back to the user to fix

their error!! no “unsigned” (as of 10/10)

o unsigned means positive range (shifts range right)o unsigned byte would be 0 to 255

Some research should go into what value your variable could possibly beo ex: IQ values can be from 0 (brain dead) to over 140

http://www.write-technical.com/126581/session2/session2.htm

What data type best fits??Variable/User Input Data type Variable/User Input Data typeTelephone (no dashes) Days in a yearSSN US CitizenDate in a Month Passengers on a Cruise ShipYes/No answer Normal home loan amount

1

Page 2: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Validation as we know it (for now) this is about to change!! Using an if-else for now (which is still necessary)

Validating with an if-elseimport java.util.Scanner;

public class Example {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int score = -1; // default value, set to 0 to fail loopboolean flag = true; // flag to track problemsSystem.out.println("Please enter your IQ to store in our

database");

score = Integer.parseInt(sc.next()); // collect data from user

if((score < 0) || (score > 200)) // picked 200 as a high value do to research

{System.out.println("Value entered not in range");flag = false;

}}

}

Please enter your IQ to store in our database5000Value entered not in rangePlease enter your IQ to store in our database200Please enter your IQ to store in our database-1200Value entered not in rangePlease enter your IQ to store in our databaseJohnnyException in thread "main" java.lang.NumberFormatException: For input string: "Johnny"

at java.lang.NumberFormatException.forInputString(Unknown Source)at java.lang.Integer.parseInt(Unknown Source)at java.lang.Integer.parseInt(Unknown Source)at Example.main(Example.java:13)

2

Page 3: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

3

Page 4: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Simple Input datatype validation Enter EVERYTHING as a STRING, then is converts it to the datatype you

wish making sure what they type in matches the datatype you asked for use a flag to track if there are any problems with the input

Validation Example (and Exercise)int score = -1; // default value, set to 0 to fail loopboolean flag = true; // flag to track problemsSystem.out.println("Please enter your IQ to store in our database");

try{

score = Integer.parseInt(sc.next()); // collect data from user}catch(NumberFormatException e){

System.out.println("Not an Integer");flag = false;

}finally // check for invalid values{

if(((score < 0) || (score > 200)) && (flag != false))// picked 200 as a high value do to research{

System.out.println("Value entered not in range");flag = false;

}}

System.out.println("Data entered was validated");

Proof it works1. Locate:

a. flag (will be used later) declaredb. String “input” declaredc. where is the String converted to a

Number? (Seen it before?)d. sc.next()?

2. What does “catch” do?3. Why was score (default value) set to 0??4. The “try” section does what, in general?5. Where is the input gathered from the

user?6. Why does the long if statement need a

set of ( ) around the OR portion?

4

Page 5: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Try/catch Blocks These will contain/recover from errors so not to END your entire application

o used for many items such as: File I/O Input from the keyboard

an error is called an EXCEPTIONo there are many methods we use the THROW an exception

try and catch and finally are reserved wordso try -> “try to do something that may cause an error”o catch -> “catch that error”

you can have SEVERAL “catches” o finally -> “do no matter what”

structure is exactly the same an if-else-ifo if Tryo else if catch(es)o else finally

Try/Catch structuredo{

try{// code that may generate an exception}catch(Exception’s_Class alias){// code to recover from the error}finally // OPTIONAL{}

} while(condition);

5

Page 6: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Using a Loop to Validate (IQ range example)

the code given only runs once, so what can we do to have it run UNTIL the user enters in the correct value

code below has the same form previous, but now in a loop

Validation using a Loopimport java.util.Scanner;

public class Example {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int score = -1; // default value, set to 0 to fail loopboolean flag = true; // flag to track problems

do{

flag = true; // flag to track problemsSystem.out.println("Please enter your IQ to store in our database");

try{

score = Integer.parseInt(sc.next()); // collect data from user}catch(NumberFormatException e){

System.out.println("Not an Integer");flag = false;

}finally // check for invalid values{

if(((score < 0) || (score > 200)) && (flag != false)){

System.out.println("Value entered not in range");flag = false;

}}

}while(flag == false);

System.out.println("Data entered was validated");}

}Please enter your IQ to store in our databaseLupoliNot an IntegerPlease enter your IQ to store in our database-1200Value entered not in rangePlease enter your IQ to store in our database201Value entered not in rangePlease enter your IQ to store in our database56Data entered was validated

1. All in light blue was the original code

6

Page 7: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

2. green is the loop

Another word about Catch In our examples, catch is only good for converting a String to some NUMBER Otherwise it is not needed

“Do While” Loops Condition is tested after body of the loop Assures program goes through at least once Non-counter loop

While – Do While Loop StructureFlowchart Example

7

Inside loop body

Yes

No

1

3 5 7

Continue outside of loop

2 64

Page 8: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Exception basics object that is created whenever an error happens

o tells you what error occurred two types

o java.lang.RunTimeException errors “thrown” during the running of your program will cover the most

o java.lang.Exception compiler errors while compiling

common java.lang.RunTimeException(s)o ArithmeticExceptiono NullPointerExceptiono IndexOutOfBoundsExceptiono IllegalArgumentExceptiono IOException

8

Page 9: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

ArithmeticException occurs when dividing AN INTEGER by 0 notice no do while loop in this example

o you (as the programmer) will have to handle what happens if the values entered are invalid

notice the various messages that can be produced when an error is throwno all options are on display here, will not be for the rest of the examples

ArithmeticException ExampleDriver codepublic class Exceptions {

// Creates a Scanner object that monitors keyboard inputstatic Scanner userInput = new Scanner(System.in);

public static void main(String[] args){

divide(6,2);divide(2,0);

}

Function/Exception Codepublic static void divide(int numerator, int denominator){

try{

System.out.println(numerator/denominator);}catch (ArithmeticException e){

// Your custom error messageSystem.out.println("1: You can't divide by zero");

// Java's error message for this exceptionSystem.out.println("2: " + e.getMessage());

// Prints the exception name and error messageSystem.out.println("3: " + e.toString());

// Prints the standard error stack traceSystem.out.print("4: ");e.printStackTrace();

}

Output3Division completed1: You can't divide by zero2: / by zero3: java.lang.ArithmeticException: / by zero4: java.lang.ArithmeticException: / by zero

at Exceptions.divide(Exceptions.java:31)at Exceptions.main(Exceptions.java:13)

Division completed

9

Page 10: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

InputMismatchException Input from the keyboard(user) does not match what was expected notice this function returns 0 if the user messed up import java.util.InputMismatchException;

InputMismatchException ExampleDriverpublic static void main(String[] args){

static Scanner userInput = new Scanner(System.in);System.out.print("How old are you? ");int age = checkValidInteger();

if (age != 0){System.out.println("You are " + age + " years old");}else{

System.out.println("Please try again.");}

}

Function/Exception Codepublic static int checkValidInteger(){

try{

return userInput.nextInt(); // nextInt() receives the user input}catch (InputMismatchException e){

userInput.next(); // Skips the last user input and waits for the nextSystem.out.println("That isn't an integer");return 0;

}}

OutputHow old are you? 23You are 161 years old in DOG years.How old are you? LupoliThat isn't an integerPlease try again.

10

Page 11: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

IndexOutOfBoundsException thrown an error when an invalid index is used to place data into an array

IndexOutOfBoundsException ExampleDriver

public static void main(String[] args){

int [] scores = new int[5];if(checkValidIntArrayPlacement(56, 8, scores)){

System.out.println("Data entry confirmed");}else{

System.out.println("Data was invalid");}

}

Function/Exception Codepublic static boolean checkValidIntArrayPlacement(int data, int index, int [] array){

try{

array[index] = data;return true;

}catch (IndexOutOfBoundsException e){

System.out.println("Data is placed in an out of bounds index number");return false;

}}

OutputData is placed in an out of bounds index numberData was invalid

11

Page 12: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

FileNotFoundException/IOException issues with any stream work notice the function either returns the connection to the stream (infile) or null also notice MULTIPLE catches in one try/catch sequence

FileNotFoundException/IOException ExampleDriver

public static void main(String[] args){

FileInputStream infile = getFile("./crap.txt");

}

Function/Exception Codepublic static FileInputStream getFile(String fileName){

FileInputStream file;try{

file = new FileInputStream(fileName);return file;

}catch (FileNotFoundException e){

System.out.println("File could not be found");}// You can catch numerous exceptions (List most specific first)catch (IOException e) // Catches any IO Exception{

System.out.println("An unknown IO Error Occured");}

// if it got here, we had an issuereturn null;

}

OutputFile could not be found

12

Page 13: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Having the function “throw” instead just another way of doing the same thing this time, no try catch inside the function the function will “throw” the error BACK to whoever called this method

o then caller has to take care of the Exceptiono so you still see a try/catch

FileNotFoundException/IOException “Thrown”Driver

public static void main(String[] args){try{

divide2(2,0);}catch (ArithmeticExpception e){

// Your custom error messageSystem.out.println("You can't divide by zero");// no finally needed

}

System.out.println("Division completed");}

Function/Exception(ish) Codepublic static void divide2(int numerator, int denominator) throws

ArithmeticException{

System.out.println(numerator/denominator);}

OutputYou can't divide by zeroDivision completed

13

Page 14: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

IllegalArgumentException Thrown to indicate that a method has been passed an illegal or inappropriate

argument. This really is a BUG in your program, this is not something to “catch”

o Hence have the function throw this error Can set the error message when you call IllegalArgumentException

IllegalArgumentException ExampleDriver

static Scanner sc = new Scanner(System.in);

public static void main(String[] args){

char result = ' ';try{

System.out.println("Enter an integer grade value");int value = sc.nextInt();result = enterGrade(value);

}catch (InputMismatchException e) // for bad input{

System.out.println("Input was an invalid type");}catch (IllegalArgumentException e)

{ System.out.println(e.getMessage());}}

Functionpublic static char enterGrade(int answer) throws IllegalArgumentException{

if((answer < 0) || (answer > 100)){

throw new IllegalArgumentException("Data entered was out of range");

}else if(answer < 60) { return 'F'; }else if(answer < 70) { return 'D'; }else if(answer < 80) { return 'C'; }else if(answer < 90) { return 'B'; }else { return 'A'; }

}OutputEnter an integer grade value-89Data entered was out of range

14

Page 15: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Converting Strings to Numbers There will be many times were the input interface will treat whatever the user

types in as a String, (JOptionPane), we can then transform that input into the format intended.

String x;int real_number;

realnumber = Integer.parseInt(x); // now “realnumber” is actually an INT value 23

Type Name Method for conversionbyte Byte.parseByte(String_to_convert)short Short.parseShort(String_to_convert)int Integer.parseInt(String_to_convert)long Long.parseLong(String_to_convert)float Float.parseFloat(String_to_convert)double Double.parseDouble(String_to_convert)

Create validation code to accept a grade (0 to 100)Things to remember:

1. What are valid ranges? May have to do some research!!2. What datatype should we be using??3. What should the default value be? (Keep it simple)

a. Default value should make the loop run again!4. What are we checking for??

a. Datatypeb. Range of values within that datatype

5. What should be used in the FINALLY section?a. If-elseb. Switch/case

Do not worry about DISPLAYING a grade.

Answerb:

15

Page 16: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Validating using JOptionPanes using a JOptionPane is GREAT in getting input

o input is always a STRING you must then convert that String to ints/doubles, etc…

o must import javax.swing.*;

Code without try/catchpublic static void main(String [] args){

int temp = -1;String name;do{

name = JOptionPane.showInputDialog(null, “Enter an Integer:”);System.out.println(“You entered “+name);

temp = Integer.parseInt(name);System.out.println(“Conversion was successful. The integer is “+temp);

}while((x > 100) || (x < 0);}

Correct Data Entered Incorrect Data Entered

16

Page 17: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Code with error checkingpublic static void main(String [] args){ int temp = -1;

String s = “”;

do{

s = JOptionPane.showInputDialog(null, "Enter an Integer:");System.out.println("You entered " + s);

try{

temp = Integer.parseInt(s);System.out.println("Conversion was successful. The integer is " + temp);

}catch(NumberFormatException z){

System.out.println("Conversion NOT successful, incompatible types.");z.printStackTrace();

}}while((temp > 100) || (temp < 0));

}

Detecting Errors Since you are getting more advanced in programming, here are some helpful

hints when things get rough Each may be adapted into what you need

17

Page 18: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Tracing simple displays USED FOR RUN TIME ERRORS ONLY!!! determine where the program jammed

o great for finding functions that are not working

Example of Tracing…System.out.println( “got here\n”); // trace statementapp.greeting();System.out.println( “got here 1\n”); // trace statementapp.calculate(x, y);System.out.println( “got here 2\n”); // trace statement…

If you only see “got here” and “got here 1”, where did the program jam??If you only see “got here”, where did the program jam??

18

Page 19: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

The Debug Clause Used when in developing the program easy to shut off when done since it uses a global boolean flag

o just set to false when you’re done can be used to show values passed in, steps the program is completing, etc.. should be placed in first few lines of EACH function

o except main( )

Debug Clause Example

public boolean debug = true; // global flag

public static void main(… ){..}

public void calculate(int x, int y, int z){

if(debug) // why not “debug = = 1”??{ System.out.println( “DEBUG: values passed into CALCULATE are: \n”); System.out.println( “int x = “ + x + “\n”); System.out.println( “int y = “ + y + “\n”); System.out.println( “int z = “ + z + “\n”);}… // rest of code

Flag Examplepublic class helloWorld {

public static boolean flag = true;

public static void main(String args[]){

if(flag) { System.out.println("The class owes Mr. L and Mr. Hughes $100"); }else { System.out.println("Mr. L and Mr. Hughes owe the class $100"); }

}}

19

Page 20: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Using Built-In tools Limits

o there are chances where the range of a datatype can be different

Using Limitspublic class helloWorld{

static Scanner sc = new Scanner(System.in); public static void main(String[] args) {

System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MAX_VALUE); System.out.println(Short.MIN_VALUE); System.out.println(Short.MAX_VALUE);

}}-21474836482147483647-3276832767

Avoiding input validation problems (if-Else)? Range check

o numbers checked to ensure they are within a range of possible values, e.g., the value for month should lie between 1 and 12.

Reasonable checko values are checked for their reasonableness, e.g. (age > 16) && (age <

100) Divide by Zero

o variables are checked for values that might cause problems such as division by zero.

Length checko variables are checked to ensure they are the appropriate length, for

example, a US telephone number has 10 digits. Format check

o Checks that the data is in a specified format (template), e.g., dates have to be in the format DD/MM/YYYY.

Available optionso Check items selected from a menu or sets of choices to ensure they are

possible options: that is, always include a default when using a switch

20

Page 21: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

Setting up from word problemsThings to remember:

1. What are valid ranges? May have to do some research!!2. What datatype should we be using??

a. If a String, then catch is NOT needed3. What should the default value be? (Keep it simple)

a. Default value should make the loop run again!4. What are we checking for??

a. Datatypeb. Range of values within that datatype

5. What should be used in the FINALLY section?a. If-elseb. Switch/case

Data Datatype String?? No catch Possible Ranges If/Else or Case

Abbr. State (US) String No Catch WIDE Range, 2 letters If/ElseZip codeRadio (freq) station (FM)

SSNAirport codeDigits (Texting) Need Catch Case

SSN Validation (the battle rages) Convert to integer, then add dashes converting it then to a String Leave as String Pros and cons of each??

21

Page 22: ecology labfaculty.cse.tamu.edu/slupoli/notes/Java/ValidationNotes.docx · Web viewdata entered into a database, sucks if you have to run back to the user to fix their error!! no

AnswersGrade Validation

import java.util.Scanner;

public class Example {

final static boolean DEBUG = true;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

byte score = -1; // default value, set to 0 to fail loopboolean flag = true; // flag to track problems

do{

flag = true; // flag to track problemsSystem.out.println("Please enter your a grade 0 - 100.");

try{

score = Byte.parseByte(sc.next());}catch(NumberFormatException e){

System.out.println("Not an Integer");flag = false;

}finally{

if(DEBUG) { System.out.println("DEBUG-> flag was: " + flag); }

if(((score < 0) || (score > 100)) && (flag != false)){

System.out.println("Value entered not in range");flag = false;

}}

}while(flag == false);

System.out.println("Data entered was validated");

}}

Sources:http://cis1.towson.edu/~cssecinj/https://www.youtube.com/watch?v=EWj60p8esD0

22