限制 Java 中用户扫描仪输入字符串中的字符数
Limiting the number of characters in a user Scanner input in String in Java
此代码应该在用户输入时打印用户名并将其长度限制为 20 个字符,但它仅在用户名超过 20 个字符时有效。当它低于 20 时我会出错。关于如何解决这个问题有什么想法吗?
谢谢。
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()));
如果将 String cutName 放在 if 中,错误应该会消失。您不能从比字符串本身长的字符串中提取子字符串。
if (name.length()>20) {
String cutName = name.substring(0, 20);
name = cutName;
}
System.out.print("Hello " +name+"!");
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
if(name.length()>20)
name = name.substring(0,20);
此代码应该在用户输入时打印用户名并将其长度限制为 20 个字符,但它仅在用户名超过 20 个字符时有效。当它低于 20 时我会出错。关于如何解决这个问题有什么想法吗?
谢谢。
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()));
如果将 String cutName 放在 if 中,错误应该会消失。您不能从比字符串本身长的字符串中提取子字符串。
if (name.length()>20) {
String cutName = name.substring(0, 20);
name = cutName;
}
System.out.print("Hello " +name+"!");
Scanner textIn = new Scanner(System.in);
System.out.print("Enter your Name ");
name = textIn.nextLine();
if(name.length()>20)
name = name.substring(0,20);