好久没发问题了!基本上我正在大学里用 Java 开始一个新项目!基本上我需要的是生成一个对象来存储其中的项目。这包括产品代码、项目名称、价格等。基本上对于产品代码,我负责决定它的长度,但它必须以字母而不是数字开头。我在想6个字符。但是我如何告诉 Java 将第一个字符保留为字母而不是数字?
非常感谢 :D
public String getProductCode(){
Random random = new Random();
int first = random.nextInt(26) + 65; //Get random ASCII code in letter range
char firstChar = new Character((char) first); //Convert to char
int suffix = 10000 + random.nextInt(89999); //Get 5 digit suffix
return Character.toString(firstChar) + String.valueOf(suffix);
}
将它们单独存储在一个对象中,并在不同的 getter 中返回组合
public class Product {
protected char id;
protected int code;
public String getFullcode() {
return id + code.toString();
}
//regular getters and setters
}
尝试这样的事情,它很hacky,但你明白了:
import java.util.Random;
public class foo {
public static void main(String args[]) {
String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
Random r = new Random();
int limit = 5;
StringBuffer buf = new StringBuffer();
buf.append(chars.charAt(r.nextInt(26)));
for (int i = 0; i < limit ; i++) {
buf.append(chars.charAt(r.nextInt(chars.length())));
}
System.out.println(buf);
}
}
只需制作两个不同的随机变量,一个选择随机字母,另一个选择任意随机字符。然后以明显的方式添加它们。希望这可以帮助
public static void main(String[] args) {
//random arrays
String[] randomLetters = {"a", "b", "c", "d", "e", "f", "g", "h", etc...}
String[] randomNumbers = {"08724 ","13876 ","29238 ","37534 ","40182 ","57532 ","69273 ", etc...};
//chooses random element from the letters
Random r = new Random();
int randl = r.nextInt(8);
String randomLetter = randomLetters[randl];
//chooses random element from the numbers
Random a = new Random();
int randn = a.nextInt(7);
String randomNumber = randomNumbers[randn];
//turns into one string and presents it
String str1 = randomLetter + randomNumber;
System.out.print(str1);
}
}
我不知道这是否正是你想要的——它是一次性的。我只是想以简单的形式做到这一点。