Function Name - ecology lab



Do While Loop, Menus & Validation

“Do While” Loops

• Condition is tested after body of the loop

• Assures program goes through at least once

|While – Do While Loop Structure |

|Flowchart Example |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

| |

|Do-While Loop |

|Programming Structure |

|Do-While |

|declare sentinel & normal variables |

| |

|do |

|{ |

|enter loop; |

|calc and display values; |

|ask and get user input |

|} while (condition) ; |

Menus

class Example

{

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

public static void main(String args[])

{

Example app = new Example();

char choice = 'z'; // default value

do

{

app.printmenu();

choice = sc.next().toUpperCase().charAt(0);

// this makes all letters uppercase regardless of

switch(choice)

{

//case '3': when coding for a NUMERIC choice

case 'L': app.go_left( ); break; // break will take you out of case

case 'R': app.go_right( ); break; // break will take you out of case

case 'Q': // no break, case will continue

case 'X': System.out.println( "Exiting Robot Program");

break; // break will take you out of case

default: System.out.println( "Invalid");

// if entry was anything but 'L', 'R', or 'X' this is what

}

}

while ((choice != 'Q') && (choice != 'X'));

}

public void printmenu( )

{

System.out.println();

System.out.println( "Please type in choice");

System.out.println( "L Move Robot Left");

System.out.println( "R Move Robot Right");

}

public void go_left ( ) { System.out.println( "You selected to go Left"); }

public void go_right ( ) { System.out.println( "You selected to go Right"); }

}

After locating the condition, determine if the input given will end the loop

|Data entered |Loop continues |Loop ends |

|T | | |

|q | | |

|S | | |

|X | | |

|R | | |

|r | | |

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

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 statement |

|app.greeting(); |

|System.out.println( “got here 1\n”); // trace statement |

|app.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??

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( “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 Example |

|public 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"); } |

|} |

|} |

Introduction to validation - 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 EXCEPTION

o there are many methods we use the THROW an exception

• try and catch and finally are reserved words

o 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-if

o if ( Try

o else if ( catch(es)

o else ( finally

|Try/Catch structure |

|do |

|{ |

|try |

|{ |

|// code that may generate an exception |

|} |

|catch(Exception’s_Class alias) |

|{ |

|// code to recover from the error |

|} |

|finally // OPTIONAL |

|{} |

|} while(condition); |

• 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/catch |

|public 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 |

|[pic] |[pic] |

|[pic] |[pic] |

|Code with error checking |

|public 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)); |

|} |

JOptionPane

• nice GUI window that received user input

• an entries are converted to a String

o that could be a problem you want to enter a number

o must use a try/catch if entering a number

o will convert after

|JOptionPane Scanarios |

|Getting Strings |

|String s = JOptionPane.showInputDialog(null, "Enter an Integer:"); |

|Getting everything else |

|int x; |

|String s; |

|do |

|{ |

|s = JOptionPane.showInputDialog(null, "Enter an Integer:"); |

| |

|try |

|{ |

|x = Integer.parseInt(s); |

|System.out.println("Conversion was successful. The integer is " + x); |

|} |

|catch(NumberFormatException z) |

|{ |

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

|z.printStackTrace(); |

|} |

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

The Problem - [pic]Integer Errors

• Integer values that are too large or too small may fall outside the allowable bounds for their data type

o reduce the robustness of your code

o lead to potential security problems.

• Variables are stored in a block of memory of a fixed size.

o means that there is a largest and smallest value that any variable of a given data type can hold.

• Where problems could happen

o operations such as addition, subtraction, and multiplication may lead to values that are outside of this range.

o Called overflows

o This can lead to a variety of problems, including security vulnerabilities

|Addition Problem example |

| |

|short a = 30,000; // max is 32,676 |

| |

|a = a + 23,000; // new total of A is what?? |

| |

|// a is now over limit!! Called Integer (short) overflow |

.

• You can check these values by:

o printing the values of the predefined constants

▪ MAX_VALUE,

▪ MIN_VALUE,

▪ etc…

|Using Limits |

| |

|public 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); |

| |

|} |

|} |

• Why is this bad?

o may be exploited to cause

o a program crash

o lead to incorrect behavior

o present opportunities for malicious software to run code that could do bad things to your computer.

Find the range of values using a RELIABLE web source!!

|Type Name |Bytes |Other Names |Range of Values |

|int |* |signed, signed int | |

|unsigned int |* |unsigned int | |

|bool |1 |none | |

|Char (Character) |1 |signed char | |

|unsigned char |1 |none | |

|short |2 |short int, signed short int | |

|unsigned short |2 |unsigned short int | |

|long |4 |long int, signed long int | |

|long long |8 |none (but equivalent to _int64) | |

|unsigned long |4 |unsigned long int | |

|enum |* |none | |

|float |4 |none | |

|double |8 |none | |

|long double |same as double |none | |

Avoiding integer overflow?

1. Choose your data types carefully:

a. If your variable will hold only positive values, such as a loop counter, declare as an unsigned int

b. Choose your data types to be large enough to hold the values you will be working with.

c. If there's any doubt at all as to whether the variable will have values that are too large for a short, use an int.

d. If an int might be too small, use a long.

2. Validate your input for ranges and reasonableness. Check input is valid and reasonable before conducting operations.

3. Check for possible overflows: Always check results of arithmetic operations on integers, to be sure that an overflow has not occurred

4. Use a library: such as SafeInt that are specifically designed to reduce the risks associated with integer operations.

1. Why is multiplication particularly risky (compared to addition)?

2. Why is user input risky?

3. Name three things that you might do in your next program to prevent an integer error from occurring.

Buffer Overflow – "Data gone wild"

• Buffer overflow occurs when data is input or written beyond the allocated bounds of an buffer, array, or other object causing a program crash or a vulnerability that hackers might exploit.

o when data is written beyond the boundaries of a fixed length buffer overwriting adjacent memory locations which may include other buffers, variables and program flow data.

o “nuclear bomb” of the software industry, the buffer overflow is one of the most persistent security vulnerabilities and frequently used attacks.

• How can it happen?

o Writing outside the bounds of a block of allocated memory can corrupt data, crash the program, or allow the execution of malicious code.

[pic]

|Buffer Overflow Example |

| |

|void main(Strings [] args) |

|{ |

|int vals = new int[10]; |

| |

|for (unsigned int i = 0; i < 20; i++) |

|{ vals[i] = i; } |

| |

|… |

|// the loop counter will exceed the value of a suitable index for the array. |

Avoiding buffer overflow problems?

1. Make sure you have enough space

a. make sure it is large enough to hold the data that you are going to copy.

b. find some way to recover from the error.

2. Validate indices

a. If you have an integer variable, verify that it is within the proper bounds before you use it as an index to an array.

b. This validation is particularly important for any values that might have been provided as user input or other untrusted input

3. When possible, use buffer-size accessor

a. Loops that iterate over arrays need to know the size of the array.

b. Using a variable with the wrong value – or the incorrect constant value – can lead to buffer overflows.

c. Some languages (Java) provide operators that can be used to retrieve the size of an array.

4. Use alternative data structures that reduce the risk of overflows

a. can be avoided by using vectors or other structures instead of traditional arrays. (Something we don’t cover yet)

1. Give three real life examples of buffer overflow attacks (research on the web).

2. How could you prevent a buffer overflow from occurring in your program?

Input Validation

• Any program input– such as a user typing at a keyboard or a network connection – can potentially be the source of security vulnerabilities. All input should be treated as potentially dangerous.

• There are four main ways to validate input

o If-else (switches)

o Loops

o Functions

o Strings

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 check

o 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 check

o 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 options

o 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

Avoiding input validation problems (Loops)?

• The do while loop is useful for input validation.

|Do While Loop Validation |

|do |

|{ |

|cout ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download