JP 4 1 Practice Solution

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Java Programming

4-1: String Processing


Practice Solutions

Vocabulary:
Identify the vocabulary word for each definition below.
Parsing Dividing a string into a set of sub-strings.
StringBuilder A class that represents a string-like object, but unlike a string can be
modified using methods such as appends.
split() A method inside the String class that parses a string by a specified
character or, if unspecified, by spaces.

Try It/Solve It:

1. You are required to use String manipulation to generate an employee’s initial values when they are added to the system. The
program will ask for their name and then generate the following values based on the information provided (Example based on
a user who provided “June Summers” as their name):
• Username:- june.summers – lowercase firstname(dot)lastname
• Email address:- [email protected] – first initial and surname followed by the email suffix
• Password:- J*l**.s* - 8-character complex password (Uppercase and lowercase characters as well as special
characters(*)).

a) Create a project named accountgenerator.

b) Create a class named Employee that has no main method and instance fields to store the unchangeable text values for the
name, username and email as well as the changeable value for the password.
public class Employee {
private final String name, username, email;
private String password;
}//end class Employee

c) Create a toString() method that will produce the following output:


Employee Details
Name : Julie Summers
Username : julie.summers
Email : [email protected]
Initial Password : J*l**.s*
Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
public String toString() {
return "Employee Details"
+"\nName : " + this.name
+"\nUsername : " + this.username
+"\nEmail : " + this.email
+"\nInitial Password : " + this.password;
}//end method toString
}//end class Employee

d) Create the following constructor showing the passing of the information to the methods.
public Employee() {
name = setName();
username = setUserName(name);
email = setEmail(username);
password = setPassword(username);
}//end constructor

e) Create a private method named countChars that will aacept a string and a char as parameters and will count the number of
times the char appears in a String. Use a for loop to go through the String and return the count of characters to the calling
method.
private int countChars(String str, char ch)
{
int count = 0;
for(int i=0; i< str.length(); i++)
{
if(str.charAt(i)==ch)
count++;
}//endfor
return count;
}//end method countChars

f) Create a setName method that accepts no parameters and returns a String value for the name. Create a count variable that
will store the return value from the countChars method and a Scanner object to read in values from the console. Use a post
tested loop to read in the user’s name until they provide a first and second name (one space in between). Send the name and
a space character to the charCounts method and exit the loop when there is a single space in the name.
private String setName() {
int charCount = 0;
Scanner in = new Scanner(System.in);
String name;
do {
System.out.print("Please enter employee's first and last name: ");
name = in.nextLine();
charCount = countChars(name, ' ');
}while(charCount!=1);
in.close();
return name;
}//end method setName

g) Create a setUserName method that accepts the String name as a parameter and returns the formatted username. The
username should be lowercase and have a dot (.) instead of a space separating the first and last names.
private String setUserName(String name) {
name = name.toLowerCase();
return name.replace(' ', '.');
}//end method setUserName

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

2
h) Create the setEmail method that accepts the username as a parameter and returns the formatted email address. The email
address is made up of the first character of the first name followed by the complete surname followed by the email address
suffix (@oracleacademy.Test).
private String setEmail(String user) {
int pos;

pos = user.indexOf('.');
return user.charAt(0) + user.substring(pos+1) + "@oracleacademy.Test";
}//end method setEmail

i) Create the setPassword method that accepts the username as a parameter and returns the complex password used for the
initial login. Set the length of the password to 8 characters, if the username is too small add additional asterisks (*) until it
reaches 8 characters. If the username is too large then restrict it to the first 8 characters. Replace all of the vowels in the
username with asterisks. A complex password requires an uppercase character so code is required to find the first alphabetic
character in the password and set that character to uppercase. Return the password to the calling method.
private String setPassword(String user) {
//8 characters, uppercase and lowercaseand a special character
int maxLength = 8;
//set the length of the initial password to 8 characters
if(user.length() < maxLength)
while(user.length() < maxLength)
user+='*';
//endwhile
else
user = user.substring(0, 8);
//endif
//replace all vowels with an asterisk
user = user.replaceAll("[aeiou]", "*");
//find the first alphabetic character and set it to uppercase
for(int i = 0; i < user.length(); i++)
if(Character.isLetter(user.charAt(i))) {
if(i==0) {
user = user.substring(0, 1).toUpperCase()
+ user.substring(1);
break;
}
else
if(i==user.length()-1) {
user = user.substring(0, i)
+ user.substring(i).toUpperCase() ;
break;
}
else {
String str1 = user.substring(0, i);
String str2 = user.substring(i, i+1).toUpperCase();
String str3 = user.substring(i+1);
user = str1+str2+str3;
break;
}
}//endif
return user;
}//end method setPassword

j) Create a driver class that creates a single Employee object and displays the value to the console using the Employee’s
toString() method.
public class AccountGenerator {
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println(emp);
Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

3
}//end method main
}//end class AccountGenerator

k) Test your code with a variety of user names.

2. Complete the following method so that it works as intended. The below method takes in a String as a parameter and returns
the reverse of the String.
public String reverse(String str){
String strRev = "";
for(int i=____________; ____; _____)
strRev+=str.charAt(__);
//endfor
return strRev;
}//end method reverse

Answer:
public class Reverse {
public static void main(String[] args) {
String start = "Lisa", ending;
ending = reverse(start);
System.out.println(ending);
}//end method main

public String reverse(String str){


String strRev = "";
for(int i=str.length()-1 ; i>=0; i--)
strRev+=str.charAt(i);
//endfor
return strRev;
}//end method reverse

}//end class Reverse

3. Would the reverse method also work for converting backwards messages back into forwards, readable messages? Why or
why not?
Answer:
Yes, because if it takes in a String that is already in reverse, the method will reverse the String, making it forwards,
and then print it out.

4. What is the major difference between making modifications to a String and a StringBuilder?

Answer:
StringBuilder can be modified but a String cannot.
Methods that appear to modify a String are actually creating a new String.

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

4
5. What does the output show if you run the following code?
public class StringvsBuilder {

public static void main(String[] args) {


String str1 = "Hello";
StringBuilder str2 = new StringBuilder("Hello");

System.out.println(str1 + " " + str1.hashCode());


System.out.println(str2.toString() + " " + str2.hashCode());

str1 = str1+ "World";


str2.append("World");

System.out.println(str1 + " " + str1.hashCode());


System.out.println(str2.toString() + " " + str2.hashCode());

}//end method main;


}//end class StringvsBuilder

Answer:
The haschcodes show that after the change the String is now a new object whereas the Stringbuilder is the same object.

6. In some situations it is easier to use a StringBuilder instead of a String. Create a program that does the same as Q2 (reverses
some text) but use a StringBuilder and one of its methods to accomplish the task.
Answer:
public class BackwardsText {

public static void main(String[] args) {


StringBuilder sb = new StringBuilder("Oracle");
backwards(sb);
System.out.println(sb);
}//end of method main

static public StringBuilder backwards(StringBuilder sb){


return sb.reverse(); // reverse it
}//end of method backwards
}//end of class BackwardsText

Copyright © 2020, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

You might also like