java - 验证数字是否在给定范围内有效,具体取决于使用的预选
问题描述
我正在编写一个生成 n 个奖金的程序,它做得很好,但是在生成他们的 ID 号时我被卡住了。此时的程序需要用户告诉程序一个Min
值和一个Max
介于10000
和之间的值10000
,直到没有问题都容易。
之后的部分让我摸不着头脑,因为程序需要知道在生成的值的给定位置可以生成多少个数字,因此它不是固定范围,生成的 id 必须且仅包含用户指定的数字对于每个 x 位置,它必须知道这一点,因此当它读取将用于该目的的值时,它们会针对其相应位置进行验证。
我尝试在工作程序中确定的某些情况下使用一些条件,但实际上我被卡住了,因为似乎必须构建很多 if 语句来包含所有可能的 id 类型发生。
// from left to right the "positions"
int min = 1 0 0 0 0;
int max = 1 0 9 9 9;
int temp = max - min;
// tells how many different digits can be used from 1 to 10 for each position (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
// leftmost position aka first
delta[0] = temp / 10000;
// aka second position
delta[1] = (temp % 10000) / 1000;
// aka third position
delta[2] = ((temp % 10000) % 1000) / 100;
// aka fourth position
delta[3] = (((temp % 10000) % 1000) % 100) / 10;
// aka fifth position
delta[4] = ((((temp % 10000) % 1000) % 100) % 10);
这些公式按预期工作,但是当给定位置重置时,公式无法说“您可以在该位置包含所有 10 位数字,因为它不仅仅是 0,而是 10000 到 10999”。
[编辑]
为了澄清上述问题,我的老师要求我执行以下操作以生成奖金 ID 编号:
询问用户一个介于 10000 和 99999 之间的范围(包括)。这意味着我只能为给定数量的奖金生成 5 位数的 ID,它们不应该重复。
还询问给定的 5 位数字范围内每个位置允许的用户编号,即我的范围从
12000 to 22000
5 位数字的左到右,用户说他只希望数字 1 出现,这样现在限制了我的ids 来生成值 from12000 to 19999
... 但他也可以说他只希望数字 2 位于该特定位置,因此也可能发生相反的情况(20000 to 22000
只能使用 from ids)。这适用于可以在最小值和最大值之间的任何给定范围内生成的所有 5 位数字。
解决方案
保留一个数字列表、随机生成您的 id 并进行比较会简单得多,如下所示:
public class IdGenerator {
private static List<Integer> usedIds = new ArrayList<>();
... (other fields and methods here)
public int generateNumber() {
// Check if all ids are used. (Redesign your ID scheme to prevent this situation, otherwise you'll run out of IDs and your application will stop working.
if (usedIds.size() >= 1000) {
throw new IllegalStateException("All allowable IDs used, please free up an ID to continue generation.");
}
// Generate a random ID with a value between 10000 and 10999.
int idCandidate = ThreadLocalRandom.current().nextInt(10000, 10999 + 1);
// ID in use, try again with new number.
if (usedIds.contains(idCandidate) {
return generateNumber();
}
// ID is not taken and can therefore be saved.
usedIds.add(idCandidate);
return idCandidate;
}
}
使用UUID更好,因为它们或多或少保证是唯一的。