InputValidation

更新时间:2023-05-09 18:15:14 阅读: 评论:0

Input Validation
When humans interact with technology, a great diversity in experience is brought to bear on the task, and things often go amiss.  If the technology is well-designed, mistakes or unusual or unexpected interactions are anticipated and accommodated in a safe and non-destructive manner.  Computer software is no exception.  When a ur enters a syntactically incorrect value or lects
a disabled feature, for example, the software must recognize, accommodate, and recover from the anomalous condition with minimal disruption.  In other words, our software must expect the unexpected.  In this ction, we will illustrate how to write simple programs that recognize and recover from invalid ur input.  We call this input validation.
Many of our programs were designed to receive input from the keyboard using the readLine() method of the BufferedReader class.  The readLine() method returns a string holding a full line of input.  If the ur entered an integer or floating point number, the string was converted
to an int using the Integer.parInt() method or to a double using the Double.parDouble() method.  For example
String s = readLine();
int value = Integer.parInt(s);
But, what if the ur entered something like "thirteen", instead of "13"?  Here's the reaction from the DemoMethod program prented earlier:
PROMPT>java DemoMethod
Enter an integer: thirteen
Exception in thread "main" java.lang.NumberFormatException: thirteen  at java.lang.Integer.parInt(Compiled Code)
at java.lang.Integer.parInt(Integer.java:458)
at DemoMethod.main(DemoMethod.java:21)
PROMPT>
Obviously, thirteen is not our lucky number.  The output is hardly what we'd call a ur-friendly error message.  The program has crashed, and we're left high and dry.  The critical term above is "NumberFormatException".  There was an attempt to par the string "thirteen" into an
int and the parInt() method didn't like what it found.  The string "thirteen" has no correspondence to an integer — at least, not in the eyes of the parInt() method.  It reacted
by throwing a "number format exception".
In this ction, we'll examine a simple way to implement input validation.  If the ur input is not correctly format, we want to gracefully recover, if possible.  And we definitely don't want our program to crash.  Input validation is well-suited to implementation in methods; so, this a good place to introduce the topic.  We'll re-visit the topic in more detail later when we examine exceptions.
The trick to input validation, as prented in this ction, is to inspect the input string before passing it to a parsing method.  If an invalid string is pard, then it's too late for graceful recovery.  We want to identify the problem before parsing, and recover in a manner that ems appropriate for the given program.  The demo program InputInteger illustrates one approach
to the problem (e Figure 1).
1  import java.io.*;
2
3  public class InputInteger
4  {
5    public static void main(String[] args) throws IOException
6    {
7        // tup 'stdin' as handle for keyboard input
8        BufferedReader stdin =
9          new BufferedReader(new InputStreamReader(System.in), 1);
10
11        // nd prompt, get input and check if valid
12        String s;
13        do
14        {
15          System.out.print("Enter an integer: ");
16          s = adLine();
17        }
18        while (!isValidInteger(s));
19
20        // convert string to integer (safely!)
21        int i = Integer.parInt(s);
22
23        // done!
24        System.out.println("You entered " + i +  " (Thanks!)");
25    }
26
27    // check if string contains a valid integer
28    public static boolean isValidInteger(String str)
29    {
30        // return 'fal' if empty string
31        if (str.length() == 0)
32          return fal;
33
34        // skip over minus sign, if prent
35        int i;
36        if (str.indexOf('-') == 0)
37          i = 1;
38        el
39          i = 0;
40
41        // ensure all characters are digits
42        while (i < str.length())
43        {
44          if (!Character.isDigit(str.charAt(i)))
45              break;
46          i++;
47        }
48
49        // if reached the end of the line, all characters are OK!
50        if (i == str.length())
51          return true;
52        el
53          return fal;
54    }
55  }
Figure 1. InputInteger.java
A sample dialogue with this program follows:
PROMPT>java InputInteger
Enter an integer:    (blank line)
Enter an integer: -  (only a minus sign entered)
Enter an integer: ninety nine  (alpha characters not allowed)
Enter an integer: -ninety nine (sorry! try again)
Enter an integer:    99  (leading spaces not allowed)
Enter an integer: 99 98 97  (no spaces allowed)
Enter an integer: 99  (finally!)
You entered 99 (Thanks!)
A variety of incorrect respons are shown above.  In all cas, the program reacted by re-issuing the prompt and inputting another line.  As evident in the 55 lines of source code, even this simple implementation of input validation is tricky.  The good news is that the input routine is packaged in a
method.  At the level of "using" the method, the code is very clean (e lines 11-18).
Let's look inside the definition of the isValidInteger() method.  For the purpo of this program, an integer string has the following characteristics: (a) it must contain no leading or trailing spaces, (b) it may contain an optional minus sign at the beginning, and (c) it must contain only digit characters until the end of the string.
The first "processing" task is to ensure that the string is not an empty string.  If the line length is zero, the method returns fal — the string does not contain a valid integer!  (See lines 30-32).  The next order of business is to check if the first character is a minus sign.  An index variable i is initialized with 0 if the first character is not a minus sign, or 1 otherwi to skip over the minus sign.  The string is scanned from this point to the end checking that each character is a digit.  The check is performed in line 44 as follows:
if (!Character.isDigit(str.charAt(i)))
The character at position i in the string is extract using the charAt() method of the String class and prented to the isDigit() method of the Character wrapper class.  The return value is true if the character is a digit, fal otherwi.  If fal is returned the relational test is true — becau of the N
OT operator ( ! ) — and the following statement exectutes.  The following statement is a break, which caus an immediate exit from the while loop.  The final value of the index variable i is either str.length() if all the characters checked out as digits or something less than str.length() if the loop terminated early.  This condition is check in line 50 and the appropriate boolean result is returned: true if the string is a valid integer, fal otherwi.
Despite the best intentions, the approach to input validation just shown is not as robust as we'd like.  If the ur enters 12345678999, for example, the program still crashes with a number format exception.  (The largest integer reprented by an int is 231 – 1 = 2,147,483,647.)  As well, it is not entirely clear that we should reject input with leading or trailing spaces.  A far better approach to input validation is to "deal with" the built-in exceptions generated by Java's API class.  We'll learn how to do this later.  For the moment, the approach shown in InputInteger will rve us well.
Since isValidInteger() is a static method, it is available to other programs, provided the InputInteger.class file is reachable by the compiler.  We could, for example, include the following lines in another Java program:
String s;
s = adLine();
if (InputInteger.isValidInteger(s))
{
/** process input **/
}
The prefix InputInteger is simply identifies the the class where the static method isValidInteger() is found, much the same as “Math” in Math.sqrt(25) identifies the class where the sqrt() method is found.

本文发布于:2023-05-09 18:15:14,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/89/875412.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图