Android随机字符串生成器

时间:2012-08-24 20:21:12

标签: android

我有问题。 我想画一个像这样的随机字符串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();
    }
}

10 个答案:

答案 0 :(得分:49)

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

你可以创建一个字符数组,其中包含你希望允许在随机字符串中的所有字符,然后在循环中从数组中取一个随机位置并添加附加到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()
}

答案 1 :(得分:47)

您的代码存在一些问题。

您无法从int转换为字符串。将它转换为char。但是这只会给你一个字符,所以你可以为字符串的长度生成一个随机数。然后运行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()而不是==

答案 2 :(得分:36)

您需要导入UUID。 这是代码

import java.util.UUID;

id = UUID.randomUUID().toString();

答案 3 :(得分:9)

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

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

答案 4 :(得分: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;
}

答案 5 :(得分:0)

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

 Random generator = new Random();
 String x = String.valueOf (generator.nextInt(96) + 32);

答案 6 :(得分: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);

答案 7 :(得分:0)

此功能在kotlin中运行->

import threading
import time
import random

class Consumer:

    def __init__(self):
        self.data = []

    def print(self):
        while True:
            print(self.data)
            time.sleep(1)

class Producer:

    def __init__(self, data):
        self.data = data

    def update(self):
        while True:
            self.data.append(random.random())
            time.sleep(1)


consumer = Consumer()
producer = Producer(consumer.data)
threading.Thread(target=consumer.print).start()
threading.Thread(target=producer.update).start()

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

答案 8 :(得分:0)

使用org.apache.commons.lang3.RandomStringUtils包快速衬纸。

String randonString = RandomStringUtils.randomAlphanumeric(16);

需要在gradle构建文件中使用库依赖项:

implementation 'org.apache.commons:commons-text:1.6'

答案 9 :(得分:0)

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

import java.util.Calendar;

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

Or

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

//Eg: output: "1602791949543"