kandaspohn kandaspohn - 2 months ago 8
Java Question

Java Exception Handling (Empty spaces in user input)

I need to create an exception class that will throw an exception when there are spaces in user input for a name, password, etc. (all strings). I have written all the code that I thought was necessary and no matter what I input, the exception is always thrown.

What am I doing wrong?

The following are snippets of code. If the whole program is needed, let me know.

EmptyInputException
class:

public class EmptyInputException extends Exception{
public EmptyInputException(){
super("ERROR: Spaces entered - try again.");
}
public EmptyInputException(String npr){
super("ERROR: Spaces entered for " + npr + " - Please try again.");
}


}

Here the
getInput
method where I catch the exception:

public void getInput() {
boolean keepGoing = true;

System.out.print("Enter Name: ");

while (keepGoing) {

if(name.equalsIgnoreCase("Admin")){
System.exit(1);
}else

try {
name = scanner.next();
keepGoing = false;
throw new EmptyInputException();

} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}//end loop
}
System.out.print("Enter Room No.:");

while (keepGoing) {
if(room.equalsIgnoreCase("X123")){
System.exit(1);
}else
try {
room = scanner.next();
if (room.contains(" ")){
throw new EmptyInputException();
}else
keepGoing = false;

} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}

System.out.print("Enter Password:");

while (keepGoing) {
if(pwd.equals("$maTrix%TwO$")){
System.exit(1);
}else
try {
pwd = scanner.next();
keepGoing = false;
throw new EmptyInputException();
} catch (EmptyInputException e) {
System.out.println("ERROR: Please do not enter spaces.");
keepGoing = true;
}
}

}


I feel like I am missing the part where the scanner input should include spaces, such as:

if(name.contains(" "))


and so on...

So far, my output (after entering a name, for example) will say,
Error: Please do not put spaces.

drx drx
Answer
try {
        name = scanner.next();
        keepGoing = false;
        if(name.contains(" "))
            throw new EmptyInputException();

    }

Should do the trick?

Comments