David
David

Reputation: 247

Print only twelve characters from user submitted string in Java

I have a user input their name as a string and then the name is printed out onto the screen. How can i limit what is printed to only 12 characters so that a user cannot type an insanely long name? Here is my code:

    Scanner input = new Scanner(System.in);
    System.out.print("Enter your player name: ");
    String name= input.next();
    System.out.print("\n" + name + " has started the game\n");

Upvotes: 0

Views: 841

Answers (2)

user4626745
user4626745

Reputation: 11

{
public static void main (String[]args){
String s = new String();
        String n = new String();
        s = "ya ali madad";
        if (s.length() > 10) {
            n = s.substring(10, 12);
        }
        System.out.println("String s:" + s);
        System.out.println("String n:" + n);}}

Upvotes: 0

Chris Dennett
Chris Dennett

Reputation: 22721

Something like:

String name = input.next();
name = name.length() > 12 ? name.substring(0, 11) : name;

and accept some of your previous answers.

Upvotes: 4

Related Questions