简体   繁体   中英

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+"!");
}

只需在20和String的长度之间取较低的索引。

name.substring(0, Math.min(20,name.length()));

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+"!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM