Search code examples
javastringinputstring-length

Limiting the number of characters in a user Scanner input in String in Java


This code is supposed to print the user's name when they enter it and limit it's length to 20 characters, but it only works when the user's name is longer than 20 chars. I get en error when it's below 20. Any ideas on how to fix this?

Thank you.

String name;

Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();

String cutName = name.substring(0, 20);
if (name.length()>20) {
    name = cutName;
System.out.print("Hello " +name+"!");
}

Solution

  • If you place your String cutName inside the if, the error should disappear. You cannot take a substring from a string that is longer than the String itself.

    if (name.length()>20) {
        String cutName = name.substring(0, 20);
        name = cutName;
    }
    
    System.out.print("Hello " +name+"!");