Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 7.7 Example: Processing Names and Passwords

Many computer systems store user names and passwords as delimited strings, such as
smith:bg1s5xxx
mccarthy:2ffo900ssi
cho:biff4534ddee4w
Obviously, if the system is going to process passwords, it needs some way to take apart these name-password pairs.
Let’s write methods to help perform this task. The first method will be passed a name-password pair and will return the name. The second method will be passed a name-password pair and will return the password. In both cases, the method takes a single String parameter and returns a String result:
String getName(String str);
String getPassword(String str);
To solve this problem we can make use of two String methods. We use the indexOf() method to find the location of the delimiter—which is the colon, “:” —in the name-password pair and then we use substring() to take the substring occurring before or after the delimiter. It may be easier to see this if we take a particular example:
INDEX:           1         2
INDEX: 012345678901234567890
       jones:b34rdffg12    // (1)
       cho:rtf546          // (2)
In the first case, the delimiter occurs at index position 5 in the string. Therefore, to take the name substring, we would use substring(0,5). To take the password substring, we would use substring(6). Of course, in the general case, we would use variables to indicate the position of the delimiter, as in the following methods:
public static String getName(String str) 
{
  int posColon = str.indexOf(':');  // Find the delimiter
  String result = str.substring(0, posColon); // Get name
  return result;
}
public static String getPassword(String str) 
{
  int posColon = str.indexOf(':');  // Find the delimiter
  String result = str.substring(posColon + 1); // Get passwd
  return result;
}
Listing 7.7.1. The getName() and getPassword() methods.
Note in both of these cases we have used local variables, posColon and result , to store the intermediate results of the computation—that is, the index of the “:” and the name or password substring.
An alternative way to code these operations would be to use nested method calls to reduce the code to a single line:
return str.substring(0, str.indexOf(':'));
In this line, the result of str.indexOf(':') is passed immediately as the second argument to str.substring(). This version dispenses with the need for additional variables. And the result in this case is not unreasonably complicated. But whenever you are faced with a trade-off of this sort —nesting versus additional variables —you should opt for the style that will be easier to read and understand.
You have attempted of activities on this page.