Jump to content

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


Guest

Recommended Posts

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!

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

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