我的想法是为每个用户创建一个唯一的ID。它包含字符和整数。 ID的前2个字母是用户名的缩写,下4个字母必须是年份,后3个字母是随机的。
public String getUserID(){
String[] ID = new String[9];
ID[0] = String.valueOf(name.charAt(1));
ID[1] = String.valueOf(surname.charAt(2));
int years = Date_Of_Birth.getYear();
int[] numOfYears = new int[4];
for(int i = 0; i < 4; i++)
{
int a = years%10;
a = numOfYears[i];
years /= 10;
ID[i] = numOfYears[i]; // Java.lang.string, not int
}
Random random = new Random();
int a = Integer.toString(random.nextInt(9)); // Java.lang.string, not int
int b = random.nextInt(9) + 1;
int c = random.nextInt(9) + 1;
ID[7] = a;
ID[8] = b;
ID[9] = c;
}
我正在努力将整数转换为字符串,反之亦然。我一直在尝试一些诸如String.valueOf()或整数之类的事情,但是一切似乎都没有希望
答案 0 :(得分:0)
检查:
public String getUserID(){
StringBuilder sb = new StringBuilder();
sb.append(name.substring(0, 1));
sb.append(surname.substring(0, 1));
sb.append(String.valueOf(Date_Of_Birth.getYear()));
Random random = new Random();
for (int i = 1; i <= 3; i++) {
int a = random.nextInt(9) + 1;
sb.append(String.valueOf(a));
}
return sb.toString();
}
它使用SringBuilder
逐步构建id:
name
的第一个字符surname
的第一个字符Date_Of_Birth.getYear()
返回4位数字)StringBuilder
的字符串答案 1 :(得分:0)
使用StringBuilder
来构造一个String
而不是String[]
数组。
Random random = new Random();
StringBuilder builder = new StringBuilder();
builder.append(name.charAt(1))
.append(surname.charAt(2))
.append(Date_Of_Birth.getYear())
.append(100 + random.nextInt(900)));
return builder.toString();
答案 2 :(得分:0)
更改后,代码看起来像这样,就我而言,我认为还可以。
public String getUserID(){
String[] IDletters = new String[2];
IDletters[0] = String.valueOf(name.charAt(1));
IDletters[1] = String.valueOf(surname.charAt(2));
int years = Date_Of_Birth.getYear();
int[] numOfYears = new int[4];
for(int i = 0; i < 4; i++)
{
int a = years%10;
a = numOfYears[i];
years /= 10;
}
Random random = new Random();
int a = random.nextInt(9)+1;
int b = random.nextInt(9)+1;
int c = random.nextInt(9)+1;
String wholeID = IDletters[0]+IDletters[1]+numOfYears[0]+numOfYears[1]+numOfYears[2]+numOfYears[3]+ a + b + c;
return wholeID;
}