可以使用正则表达式来限制用户输入的内容,以下是一个示例代码: ```java import java.util.Scanner; public class OnlyLetters { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input; do { System.out.print("请输入只包含字母的字符串:"); input = scanner.nextLine(); } while (!input.matches("[a-zA-Z]+")); System.out.println("输入的字符串为:" + input); } } ``` 在上面的代码中,使用了 `Scanner` 类来获取用户输入的字符串,然后使用 `matches()` 方法来判断输入的字符串是否只包含字母。正则表达式 `[a-zA-Z]+` 表示只包含大小写字母的字符串,其中 `+` 表示至少匹配一次。如果用户输入的字符串不符合要求,则会提示用户重新输入,直到输入符合要求为止。