JAVA判断字符串是否符合要求

键盘录入一个字符串,该字符串必须是数字开头且长度不能小于7,
如不符合要求则要继续输入,如果输入的字符串符合要求,则截取前
三位打印到控制台。

public class JudStr {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        while (true) {
            if (Character.isDigit(str.charAt(0))) {
                if (str.length() >= 7) {
                    for (int i = 0; i < 3; i++) {
                        char[] str1 = str.toCharArray();
                        System.out.print(str1[i] + " ");
                    }
                    break;
                }
            }
        }
    }
}

可以使用正则解决

public class Demo {
    public static void main(String[] args) {
        boolean run = true;
        while (run) {
            Scanner sc = new Scanner(System.in);
            String str = sc.nextLine();
            String pattern = "^[0-9].{6,}$";

            Pattern r = Pattern.compile(pattern);
            Matcher m = r.matcher(str);
            if (m.matches()) {
                System.out.println(str.substring(0, 3));
                run = false;
            }else {
                System.out.println("请输入符合要求的字符串");
            }
        }
    }
}