[英]Testing string for ascending order
I have written a piece of code here to generate a random PIN number of a specified length. 我在这里写了一段代码来生成指定长度的随机PIN码。 The code works fine but I want to add an exception where a PIN would be invalid if it ends up in ascending order.
该代码工作正常,但我想添加一个例外,如果该密码以升序结尾,则PIN无效。 For example if a PIN ended up being 1234, 3456, 4567 they would be invalid PINs.
例如,如果PIN最终为1234、3456、4567,则它们将是无效的PIN。
public static String generatePin(int nmrPinDigits)
{
String pin = new String();
NUMBER_PIN_DIGITS = nmrPinDigits;
for(int i = 0; i < NUMBER_PIN_DIGITS; i += 1)
{
double rnd = Math.random();
rnd *= 9;
rnd += 1;
byte rndByte = (byte)rnd;
String rndStr = Byte.toString(rndByte);
pin += rndStr;
}
return pin;
}
Actually the question of the OP is probably more to know if the pin is a sequence. 实际上,OP的问题可能更多是要了解引脚是否为序列。 In which case:
在这种情况下:
char prev = pin.charAt(0);
for (char ch : pin.substring(1).toCharArray()) {
if (chr - prev != 1) {
// Not a sequence
return false;
}
prev = chr;
}
// Is a sequence !
return true;
Same goes for descending order, just with -1
as a test value. 降序也是如此,只是将
-1
作为测试值。
The simplest solution would be to compare each random digit generated in your loop to the previous one. 最简单的解决方案是将循环中生成的每个随机数字与上一个数字进行比较。 If the difference is +1, discard the digit and generate another one.
如果差异为+1,则丢弃该数字并生成另一个数字。
This is the method to detect ascending or descending string.. 这是检测升序或降序字符串的方法。
public static boolean checkForAscendingOrDescendingPart(String txt, int l)
{
for (int i = 0; i <= txt.length() - l; ++i)
{
boolean success = true;
char c = txt.charAt(i);
for (int j = 1; j < l; ++j)
{
if (((char) c + j) != txt.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
success = true;
for (int j = 1; j < l; ++j)
{
if (((char) c - j) != txt.charAt(i + j))
{
success = false;
break;
}
}
if (success) return true;
}
return false;
}
Call this method before returning pin..and throw exception there..like.. 返回pin之前调用此方法,然后在其中抛出异常。
checkForAscendingOrDescendingPart(pin, pin.length());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.