Android随机字符串生成器?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (56)

想绘制一个随机的字符串像这样aXcFg3s2。

private String random;
private String charsEntered;
private EditText et;
private Button ok;
CaptchaInterface.OnCorrectListener mCorrectListener;

public void setOnCorrectListener(CaptchaInterface.OnCorrectListener listener) {
    mCorrectListener = listener;
}

public TextCaptcha(Context context) {
    super(context);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
}

public static String random() {
    Random generator = new Random();
    String x = (String) (generator.nextInt(96) + 32);
    return x;
}

public void onCreate(Bundle icicle) {
    setContentView(R.layout.main);
    random = random();
    TextView display = (TextView) findViewById(R.id.textView1);
    display.setText("Random Number: " + random); // Show the random number
    et = (EditText) findViewById(R.id.etNumbers);
    ok = (Button) findViewById(R.id.button1);
    ok.setOnClickListener(this);

}

public void onClick(View arg0) {
    // TODO Auto-generated method stub
    try {
        charsEntered = et.getText().toString();
    } catch (NumberFormatException nfe) {
        Toast.makeText(et.getContext(), "Bla bla bla",
                Toast.LENGTH_LONG).show();
    }

    if (random == charsEntered) {
        Toast.makeText(et.getContext(), "Good!", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(et.getContext(), "Bad!", Toast.LENGTH_LONG).show();
    }
}
提问于
用户回答回答于

你的代码有一些错误。

您不能从int转换为字符串。将其转换为char。然

例:

public static String random() {
    Random generator = new Random();
    StringBuilder randomStringBuilder = new StringBuilder();
    int randomLength = generator.nextInt(MAX_LENGTH);
    char tempChar;
    for (int i = 0; i < randomLength; i++){
        tempChar = (char) (generator.nextInt(96) + 32);
        randomStringBuilder.append(tempChar);
    }
    return randomStringBuilder.toString();
}

另外,你应该使用random.compareTo()而不是==

用户回答回答于

这是我建议的简单算法:

private static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm";

private static String getRandomString(final int sizeOfRandomString)
  {
  final Random random=new Random();
  final StringBuilder sb=new StringBuilder(sizeOfRandomString);
  for(int i=0;i<sizeOfRandomString;++i)
    sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
  return sb.toString();
  }

扫码关注云+社区

领取腾讯云代金券