0

Enter the player name. The name must be between 1 and 6 characters in length and not begin or end with a space character. If not meet the requirement reenter the name.

import java.util.Scanner;

public class Player
{

    public void acceptName()
    {
        System.out.println("Please enter playrname");
        Scanner scanner = new Scanner(System.in);
        String playerName = scanner.nextLine();
        while(playerName.length() < 1 || playerName.length() > 6)
        {
            System.out.println("Name length over 6,Please re-enter playername");
            playerName = scanner.nextLine();
        }            
    }        
}
Pavel Smirnov
  • 4,421
  • 3
  • 17
  • 26
  • Possible duplicate of [Java - Trim leading or trailing characters from a string?](https://stackoverflow.com/questions/25691415/java-trim-leading-or-trailing-characters-from-a-string) – Xatoo Apr 05 '19 at 06:58

4 Answers4

3

String.trim() will remove leading and trailing spaces, so comparing the length of the original string with the length of the trimmed one, should do the trick :

boolean hasLeadingOrTrailingSpaces = playerName.trim().length() != playerName.length();
Arnaud
  • 16,865
  • 3
  • 28
  • 41
3

You can check it with Character.isWhitespace() function:

if (Character.isWhitespace(playerName.charAt(0)) 
  || Character.isWhitespace(playerName.charAt(playerName.length() - 1)) {
   //do your stuff
}
Pavel Smirnov
  • 4,421
  • 3
  • 17
  • 26
1

You can use something like

if(playerName.startsWith(" ")||playerName.endsWith(" ")){
        System.out.println("Incorrect name;
}
Dred
  • 916
  • 7
  • 22
0
  1. Find length of entered string
  2. Perform (String.trim()).length()
  3. Compare length ..
Pavel Smirnov
  • 4,421
  • 3
  • 17
  • 26
HS447
  • 59
  • 8