此代碼在輸入用戶名時應將其打印出來,並將其長度限制爲20個字符,但僅當用戶名長於20字符。當它低於20時,我會遇到錯誤。關於如何解決此問題的任何想法?限制用戶中的字符數在Java中的字符串中輸入的掃描器輸入
謝謝。
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+"!");
}
你必須在做子串之前做長度檢查。你可以使用:'String cutName = name.length()<= 20? name:name.substring(0,20);' – ParkerHalo
set System.out.print(「Hello」+ name +「!」);出循環 –