对于此作业,我需要接受锁定组合并检查是否:
我想知道是否有更好的方法来检查数字的每个位置?
Scanner input = new Scanner(System.in);
String lockComb;
System.out.print("Please enter a lock combination ( ddRddLddR ): ");
lockComb = input.nextLine();
if((lockComb.length() == 9) && ((lockComb.charAt(2) == 'r') || (lockComb.charAt(2) == 'R')) &&
((lockComb.charAt(5) == 'l') || (lockComb.charAt(5) == 'L')) && ((lockComb.charAt(8) == 'r')
|| (lockComb.charAt(8) == 'R')))
{
if((Character.isDigit(lockComb.charAt(0))) && (Character.isDigit(lockComb.charAt(1))) &&
(Character.isDigit(lockComb.charAt(3)) && (Character.isDigit(lockComb.charAt(4))) &&
(Character.isDigit(lockComb.charAt(6))) && (Character.isDigit(lockComb.charAt(7)))))
{
System.out.println(lockComb + " is a valid lock combination!");
}
else
{
System.out.println(lockComb + " is not a valid lock combination!");
}
}
else
{
System.out.println(lockComb + " is not a valid lock combination!");
}
答案 0 :(得分:6)
为简化起见,您可以使用正则表达式:
if (lockComb.matches("[0-9][0-9][rR][0-9][0-9][lL][0-9][0-9][rR]")
(中间是小写-1和大写-L。)
(无需检查长度,这是由正则表达式隐式定义的。)
答案 1 :(得分:2)
如果只是为了获得一个不涉及正则表达式的解决方案。我根本不是仅仅针对不同的解决方案而反对。如果使用正则表达式,你会失去一件事就是能够确切地说明为什么这不是一个有效的锁组合。根据您编写的方案,您可以自行决定最佳解决方案。
public static boolean matcher (String lockComb) {
if(lockComb.length() != 9) {
System.out.println(lockComb + " is not a valid lock combination!");
return false;
}
boolean isValid = true;
char[] comb = lockComb.toUpperCase().toCharArray();
for (int i = 0; i < comb.length; i++) {
switch (i) {
case 2:
case 8:
isValid = (comb[i] == 'R');
break;
case 5:
isValid = (comb[i] == 'L');
break;
default:
isValid = Character.isDigit(comb[i]);
break;
}
if(isValid == false) break;
}
if(isValid) {
System.out.println(lockComb + " is a valid lock combination!");
} else {
System.out.println(lockComb + " is not a valid lock combination!");
}
return isValid;
}