Hope some smart guys can help me with this Java! Thank you! Consider a system th
ID: 3686096 • Letter: H
Question
Hope some smart guys can help me with this Java! Thank you!
Consider a system that requires unique user names. A method called checkUserName (below) takes in a user name and a list of existing names. If the user name already exists, this is considered an erroneous situation.
There are three parts to this question:
Part A: Write the class to represent the erroneous situation.
Part B: Write code to use this class to indicate the error has occurred.
Part C: Does your Part B code require any changes to the method header?
// Part A: Write your own class to represent the erroneous situation.
public void checkUserName(String userName, ArrayList<String> existingNames) { // Part C: Any changes required to the method header based on your code in Part B?
if(existingNames.contains(userName) {
// Part B: What code goes here?
} else {
existingNames.add(userName);
}
}
Explanation / Answer
/**The java program that throws an error message if the duplicate value is passed to the checkUserName
* method using DuplicateNameError class.
Create a Class called DuplicateNameError that handles the exceptio for part B
*/
//PartA program
//ArrayListProgram.java
import java.util.ArrayList;
public class ArrayListProgram {
public static void main(String[] args) throws DuplicateNameError {
//Create an ArrayList of type string
ArrayList<String>names=new ArrayList<String>();
names.add("Johnson");
names.add("Micheal");
names.add("Gupta");
names.add("Singh");
//calling checkUserName
checkUserName("Gupta", names);
}
/**The method checkUserName that takes string user name and
* an ArrayList as input arguments and calls the method contains
* to check if the username is exists then thorws an exception
* DuplicateNameError */
public static void checkUserName(String userName, ArrayList<String> existingNames) throws DuplicateNameError
{
if(existingNames.contains(userName)) {
throw new DuplicateNameError(userName+" is already exists.");
} else {
//otherwise call add method to username to the existingNames array
existingNames.add(userName);
}
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
//DuplicateNameError.java
//The class DuplicateNameError that extends the Exception class
public class DuplicateNameError extends Exception{
//constructor that takes string name and
//calls the super class with name
public DuplicateNameError(String name) {
super(name);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
Sample output:
Exception in thread "main" DuplicateNameError: Gupta is already exists.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.