我正在使用Java制作预订系统,我想创建随机ID号。 (我要显示的代码不是我班级中的所有代码,只是与之相关的内容。)
我已经命名了一个字段randomGenerator,它是一个Random对象并在我的构造函数中声明它:
public class ReservationSystem {
private Random randomGenerator;
public ReservationSystem() {
randomGenerator = new Random();
}
然后这是我遇到困难的方法:
public void generateCustomerID(String id, int numbersInID) {
//incNumber stands for incremented number
int incNumber = 1;
//create a new array of numbers as big as the user has defined
int[] numbers = new int[numbersInID];
while(numbersInID < (incNumber +1)) {
//add a new number to the array between 0 and 10
numbers[incNumber] = randomGenerator.nextInt(10);
incNumber++;
}
System.out.print(id);
for(int number: numbers)
System.out.print(number);
}
在我的申请中,我已经给出了这些价值观:
public class Application {
public static void main(String[] args) {
reserve.generateCustomerID("AB-", 3);
}
}
我一直在收到输出 AB-000 。
答案 0 :(得分:1)
numbersInID < (incNumber +1)
错误,当numbersInID
为3时,循环体不会被执行。试试这个:
public void generateCustomerID(String id, int numbersInID) {
//incNumber stands for incremented number
int incNumber = 0;
//create a new array of numbers as big as the user has defined
int[] numbers = new int[numbersInID];
while(incNumber < numbersInID) {
//add a new number to the array between 0 and 10
numbers[incNumber] = randomGenerator.nextInt(10);
incNumber++;
}
System.out.print(id);
for(int number: numbers)
System.out.print(number);
}
答案 1 :(得分:1)
问题在于:
while(numbersInID < (incNumber +1)) { // ← *here*
//add a new number to the array between 0 and 10
numbers[incNumber] = randomGenerator.nextInt(10);
incNumber++;
}
应该是numbersInID
更大而不是incNumber
:
int incNumber = 0;
while(numbersInID > incNumber) {
//add a new number to the array between 0 and 10
numbers[incNumber] = randomGenerator.nextInt(10);
incNumber++;
}