41

我有个问题。我想绘制一个随机字符串,例如 aXcFg3s2。我在做什么坏事?如何改变我的random()

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();
    }
}
4

10 回答 10

74

问题是您只处理了一个字符而不是使用循环。

您可以创建一个字符数组,其中包含您希望允许出现在随机字符串中的所有字符,然后在循环中从数组中获取一个随机位置并将其添加到 stringBuilder 中。最后,将 stringBuilder 转换为字符串。


编辑:这是我建议的简单算法:

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();
  }

在 Kotlin 上:

companion object {
    private val ALLOWED_CHARACTERS = "0123456789qwertyuiopasdfghjklzxcvbnm"
}

private fun getRandomString(sizeOfRandomString: Int): String {
    val random = Random()
    val sb = StringBuilder(sizeOfRandomString)
    for (i in 0 until sizeOfRandomString)
        sb.append(ALLOWED_CHARACTERS[random.nextInt(ALLOWED_CHARACTERS.length)])
    return sb.toString()
}
于 2012-08-24T20:27:58.513 回答
59

您的代码有一些问题。

您不能从 int 转换为字符串。改为将其转换为字符。但是,这只会给您一个字符,因此您可以为字符串的长度生成一个随机数。然后运行 ​​for 循环以生成随机字符。您也可以定义一个 StringBuilder 并将字符添加到其中,然后使用该toString()方法获取您的随机字符串

例子:

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()而不是 ==

于 2012-08-24T20:39:18.747 回答
52

您需要导入 UUID。这是代码

import java.util.UUID;

id = UUID.randomUUID().toString();
于 2015-11-06T09:52:21.887 回答
11

这就是我生成具有所需字符和所需长度的随机字符串的方式

          char[] chars1 = "ABCDEF012GHIJKL345MNOPQR678STUVWXYZ9".toCharArray();
                                StringBuilder sb1 = new StringBuilder();
                                Random random1 = new Random();
                                for (int i = 0; i < 6; i++)
                                {
                                    char c1 = chars1[random1.nextInt(chars1.length)];
                                    sb1.append(c1);
                                }
                                String random_string = sb1.toString();  
于 2014-09-08T10:29:21.373 回答
2

这个函数在 kotlin 中运行 ->

fun randomString(stringLength: Int): String {
    val list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray()
    var randomS = ""
    for (i in 1..stringLength) {
        randomS += list[getRandomNumber(0, list.size - 1)]
    }
    return randomS
}

fun getRandomNumber(min: Int, max: Int): Int {
   return Random().nextInt((max - min) + 1) + min
}

或者你可以使用我的图书馆 https://github.com/Aryan-mor/Utils-Library

于 2019-06-05T13:52:34.497 回答
1

您可以简单地使用以下方法生成 5 个字符的随机字符串,它将返回随机字符串的 arrayList

public ArrayList<String> generateRandomString() {

    ArrayList<String> list = new ArrayList<>();
    Random rnd = new Random();
    String str = "";

    String randomLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String randomLetterSmall = "abcdefghijklmnopqrstuvwxyz";

    for (int n = 0; n < 50; n++) {
        str = String.valueOf(randomLetters.charAt(rnd.nextInt(randomLetters.length())));

        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));
        str += String.valueOf(randomLetterSmall.charAt(rnd.nextInt(randomLetters.length())));

        //Copy above line to increase character of the String
        list.add(str);
    }
    Collections.sort(list);
    return list;
}
于 2017-09-25T11:37:45.423 回答
0

您不能将 int 强制转换为 String。尝试:

 Random generator = new Random();
 String x = String.valueOf (generator.nextInt(96) + 32);
于 2012-08-24T20:27:33.227 回答
0
final  String[] Textlist = { "Text1", "Text2", "Text3"};

TextView yourTextView = (TextView)findViewById(R.id.yourTextView);

Random random = new Random();

String randomText = TextList[random.nextInt(TextList.length)];

yourTextView.setText(randomText);
于 2015-06-26T12:59:42.860 回答
0

org.apache.commons.lang3.RandomStringUtils使用包装快速一个班轮。

String randonString = RandomStringUtils.randomAlphanumeric(16);

需要 gradle 构建文件中的库依赖项:

implementation 'org.apache.commons:commons-text:1.6'
于 2019-11-06T01:48:42.983 回答
0

您可以简单地将当前时间(以毫秒为单位)转换为字符串,例如

import java.util.Calendar;

String newRandomId = String.valueOf(Calendar.getInstance().getTimeInMillis());

Or

String newRandomId = Calendar.getInstance().getTimeInMillis() + "";

//Eg: output: "1602791949543"
于 2020-10-22T22:39:21.917 回答