用什么方法实现短信验证码

 public static String getNum(){
    Random random=new Random();
    String num=random.nextInt(10000)+"";
    if(num.length()!=4){  
      return getNum();  
  }  
    return num;
  }

这种方法不知道可行吗

阅读 3.2k
3 个回答
String str = Double.toString(Math.random()).replace("0.", "");

你可以从这个字符串里面任意截取就行

你这个可能会出现java.lang.StackOverflowError的情况

生成4位的验证码还用到递归……我也是醉了

public static String getNum() {
    Random random = new Random();
    char[] code = new char[4];
    for (int i = 0; i < code.length; i++) {
        code[i] = (char) (48 + random.nextInt(10));
    }
    return new String(code);
}

还有个更简单的

public static String getNum() {
    Random random = new Random();
    int code = 1000 + random.nextInt(10000 - 1000);
    return Integer.toString(code);
}

顺便,你看看我这个代码格式,和你那个代码格式,哪个看起来更清楚?注意缩进呵。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题