简体   繁体   中英

Extra java input validation for strings

I want to make this so that short inputs can still be detected, such as "Londo" and "Lon", but want to keep it small and use it without basically copying and pasting the code, any tips? thank you.

if (Menu.answer1.equals("London"))
        {
         if (location.equals("London")) {
             System.out.print(location + " ");
             System.out.print(date + " ");
             System.out.print(degrees + "C ");
             System.out.print(wind + "MPH ");
             System.out.print(winddirection + " ");
             System.out.print(weather + " ");
             System.out.println("");
         }

You can use startsWith()

String city = "London";
if (city.startsWith("Lon")) {
    // do something
}

Also if you need to check some substring, you can use contains method:

Menu.answer1 = "London";
Menu.answer1.contains("ondo"); // true

If you want to check against a fixed set of alternatives, you may use a list of valid inputs using contains :

List<String> londonNames = Arrays.asList("London", "Londo", "Lon");
if (londonNames.contains(Menu.answer1)) {
 ...
}

You can use ( case-insensitive ) regex to do the same, eg:

(?)Lon[az]{0,3} where

  • (?) = case insensitivity
  • Lon = Initial 3 characters
  • [az]{0,3} = any number of alphabets between 0 and 3

Here's an example:

String regex = "(?)Lon[a-z]{0,3}";
System.out.println("London".matches(regex));
System.out.println("Lond".matches(regex));
System.out.println("Lon".matches(regex));

If the underlying problem is that the user can enter one of several names, and you want to allow abbreviations, then a fairly standard approach is to have a table of acceptable names.

Given the user input, loop through the table testing "does the table entry start with the string typed by the user?" (like one of the previous answers here). If yes, then you have a potential match.

Keep looking. If you get a second match then the user input was ambiguous and should be rejected.

As a bonus, you can collect all names that match, and then use them in an error message. ("Pick one of London, Lonfoo, Lonbar").

This approach has the advantage (compared to a long chain of if-then-else logic) of not requiring you to write more code when all you want to do is have more data.

It automatically allows the shortest unique abbreviation, and will adjust when a once-unique abbreviation is no longer unique because of newly-added names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM