91.3k views
4 votes
public class UserName 1/ The list of possible user names, based on a user's first and last names and initialized by the constructor private ArrayList possibles ; /* Constructs a UserName object as described in part (a). • Precondition: firstName and lastNane have length greater than a and contain only uppercase and lowercase letters. public UserName(String firstName, String lastName) {/" to be implemented in part (a) */) /** Returns true if arr contains name, and false otherwise. */ public boolean isused(String name, Strinell arr) [/" implementation not shown ) /* Removes strings from possibleNames that are found in usedNames as described in part (6) public void setAvailableUserNames(Strinel) usedNames) { 1 to be implemented in part (6) (a) Write the constructor for the UserName class. The constructor initializes and fills possibleNames with possible user names based on the firstName and lastName parameters. The possible user names are obtained by concatenating lastName with different substrings of firstName. The substrings begin with the first character of firstName and the lengths of the substrings take on all values from 1 to the length of firstName.

1 Answer

4 votes

Answer: Provided in the explanation segment

Step-by-step explanation:

CODE:-

import java.util.*;

class UserName{

ArrayList<String> possibleNames;

UserName(String firstName, String lastName){

if(this.isValidName(firstName) && this.isValidName(lastName)){

possibleNames = new ArrayList<String>();

for(int i=1;i<firstName.length()+1;i++){

possibleNames.add(lastName+firstName.substring(0,i));

}

}else{

System.out.println("firstName and lastName must contain letters only.");

}

}

public boolean isUsed(String name, String[] arr){

for(int i=0;i<arr.length;i++){

if(name.equals(arr[i]))

return true;

}

return false;

}

public void setAvailableUserNames(String[] usedNames){

String[] names = new String[this.possibleNames.size()];

names = this.possibleNames.toArray(names);

for(int i=0;i<usedNames.length;i++){

if(isUsed(usedNames[i],names)){

int index = this.possibleNames.indexOf(usedNames[i]);

this.possibleNames.remove(index);

names = new String[this.possibleNames.size()];

names = this.possibleNames.toArray(names);

}

}

}

public boolean isValidName(String str){

if(str.length()==0) return false;

for(int i=0;i<str.length();i++)str.charAt(i)>'z' && (str.charAt(i)<'A'

return true;

}

public static void main(String[] args) {

UserName person1 = new UserName("john","smith");

System.out.println(person1.possibleNames);

String[] used = {"harta","hartm","harty"};

UserName person2 = new UserName("mary","hart");

System.out.println("possibleNames before removing: "+person2.possibleNames);

person2.setAvailableUserNames(used);

System.out.println("possibleNames after removing: "+person2.possibleNames);

}

}

cheers i hope this helped !!

User Srilakshmikanthanp
by
3.4k points