Jump to content

Can somebody please eli5 "sanitizing input" for me with a Java exemplar


Recommended Posts

Posted

The tutorial I am following says that:

"Post-test loops will execute at least ONE TIME - This is useful for sanitizing input"

 

I have no idea what this means. Help please!

Posted (edited)
7 minutes ago, Noidlox said:

The tutorial I am following says that:

"Post-test loops will execute at least ONE TIME - This is useful for sanitizing input"

 

I have no idea what this means. Help please!

An example of a post-test loop would be a do while loop.

For example:

do {
    // some stuff
} while(some condition is true); // check this after

The contents of this loop will execute at least once, because the condition is checked after the loop completes NOT before.

This is different from a while loop where the condition is checked first:

while (some condition is true) { // Check this first
  // some stuff
}

An example use of this is sanitizing input because you may want to get some input from the user THEN check it, and only exit the loop if some condition is matched.

Consider this trivial example:

Scanner scanner = new Scanner(System.in);
String input;
do {
    input = scanner.nextLine(); // Read a line of input
} while (!input.equals("Hello")); // Only exit the loop if the input matches "Hello"

 

Edited by Explv
  • Like 4
Posted
4 minutes ago, Explv said:

An example of a post-test loop would be a do while loop.

For example:


do {
    // some stuff
} while(some condition is true); // check this after

The contents of this loop will execute at least once, because the condition is checked after the loop completes NOT before.

This is different from a while loop where the condition is checked first:


while (some condition is true) { // Check this first
  // some stuff
}

An example use of this is sanitizing input because you may want to get some input from the user THEN check it, and only exit the loop if some condition is matched.

Consider this trivial example:


Scanner scanner = new Scanner(System.in);
String input;
do {
    input = scanner.nextLine(); // Read a line of input
} while (!input.equals("Hello")); // Only exit the loop if the input matches "Hello"

 

Makes sense. Thank you!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...