RJobber
RJobber

Reputation: 23

Validate name to not be blank

I wrote a method that asks the user to input a name, but I don't want it equal to the compName and I don't want the user's input to be blank. I have humanName.equals("") but that will only make sure that the name isn't "". It could still be one or more blank spaces. I need there to be atleast one character there. I can't figure out how to go about doing this.

public String getHumanName(String compName){
  System.out.println("Enter a name for the human player: ");
  String humanName = scan.nextLine();
  while(humanName.equals(compName) || humanName.equals("")){
        System.out.println("The human player cannot have the same name as the computer player or be blank. Enter a new name for the human player: ");
        humanName = scan.nextLine();
  }
  return humanName;
}

Upvotes: 2

Views: 1243

Answers (4)

Magus
Magus

Reputation: 15124

You can use a combination of String#trim and equals.

while (humanName.equals(compName) || humanName == null || "".equals(humanName.trim()))

Upvotes: 2

LenglBoy
LenglBoy

Reputation: 1441

There are different ways to manages it.

  • trim() the input so blanks will be removed and you just need to check against EMPTY
  • Use the hibernate validator with @NotBlank - working for java SE and EE.

Upvotes: 0

Hussein Fawzy
Hussein Fawzy

Reputation: 366

You can use the trim() method of strings in Java to remove leading to trailing spaces of a String.

public String getHumanName(String compName){
  System.out.println("Enter a name for the human player: ");
  String humanName = scan.nextLine();

  humanName = humanName.trim();

  while(humanName.equals(compName) || humanName.equals("")){
        System.out.println("The human player cannot have the same name as the computer player or be blank. Enter a new name for the human player: ");
        humanName = scan.nextLine();

        humanName = humanName.trim();
  }
  return humanName;
}

Upvotes: 0

Federico klez Culloca
Federico klez Culloca

Reputation: 27139

Use trim() to eliminate extra spaces at the beginning or the end of a string.

while(humanName.equals(compName) || humanName.trim().equals("")){

Upvotes: 3

Related Questions