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,611
  • 3
  • 18
  • 28
陈禹旭
  • 1
  • 1
  • 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) – Sander Toonen 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
  • 17,229
  • 3
  • 31
  • 44
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,611
  • 3
  • 18
  • 28
1

You can use something like

if(playerName.startsWith(" ")||playerName.endsWith(" ")){
        System.out.println("Incorrect name;
}
Dred
  • 1,076
  • 8
  • 24
0
  1. Find length of entered string
  2. Perform (String.trim()).length()
  3. Compare length ..
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28
HS447
  • 81
  • 9