要求用户在控制台输入自己的用户名 然后要求用户名不能为空 必须20字以内

img

这里主要用到Scanner类,并结合while循环控制、条件控制等程序思想,设置一个变量存储结束运行标志等

    public static void main(String[] args) {
        System.out.println("请输入用户名称(按回车结束):");
        Scanner sc = new Scanner(System.in);
        boolean result = true;
        while(result){
          String content =  sc.nextLine();
          if(content == null || content.trim().length() == 0){
              System.out.println("用户名称为空,请重新输入:");
          }else if(content.length() > 20){
              System.out.println("用户名称超过20个字符,请重新输入:");
          }else {
              result = false;
          }
        }

        System.out.println("程序结束!");
    }