The importance of data security allows us to restrict the user from providing invalid input. In order to avoid a problem or a “bug” in the software, you must restrict the user’s input with some interval of possible values
Example: Write a program that asks the user to enter a value between 0-5. If the user provides you with invalid input, your program shall run again until the user satisfies the request.
· Selection of loop: Do-while, since we will ask for the user’s input first
· What is the condition:
While input < 0 || input > 5
While input >= 0 && input <= 5
You have three options to validate user input:
Option #1 Validating by flipping the logic (post-test)
int x;
do{
System.out.println("Enter a number [0,5]");
x = input.nextInt();
}while(x < 0 || x > 5);
System.out.println("Thank you");
Option #2: Sentinel or Flags
int n;
boolean sentinel = true;
while(sentinel)
{
System.out.println("Please enter a value between 0 and 5");
n = input.nextInt();
if(n >= 0 && n <= 5)
sentinel = false;
}
System.out.println("Thank you for entering the correct value");
Option #3: Making an infinite loop and use the break “emergency exit”
while(true)
{
System.out.println("Please enter a value between 0 and 5");
int n = input.nextInt();
if(n >= 0 && n <= 5){
break;
}
}
System.out.println("Thank you for entering the correct value");
AP CS A
[while Loop]
CON-2.H Compute statement execution counts and informal run-time comparison of iterative statements.
CON-2.H.1 A statement execution count indicates the number of times a statement is executed by the program.
[do-while Loop]
CON-2.C.1 Iteration statements change the flow of control by repeating a set of statements zero or more times until a condition is met.
[Random Numbers]
CON-1.D.4 The values returned from Math.random can be manipulated to produce a random int or double in a defined range
Explain the importance of algorithms in the problem-solving process.
Demonstrate how a problem may be solved by multiple algorithms, each with different properties.
Read a given program, and explain what it does
Trace the flow of control during the execution of a program (both correct and incorrect).
Use appropriate terminology to identity elements of a program (e.g., identifier, operator, operand)
Reading and explaining code
Basic concepts such as variables, primitive data types, expression evaluation, assignment, etc.