基本上我试图让一些while循环检查字符串中的特定索引。验证refNum长度的第一个循环工作正常。当它进入更大的while循环时它只是跳过它而我不确定为什么,任何反馈都会非常感激。
package testing_code;
import java.util.Scanner;
/**
*
* @author A.Con
*/
public class Testing_Code
{
public static void main(String[] args)
{
Scanner userInput = new Scanner (System.in);
String refNum;
System.out.println("Enter refNum: example - WE123A");
refNum = userInput.next();
int rnLength = refNum.length();
while(rnLength < 6 || rnLength > 6)
{
System.out.println("Invalid reference number. Try again.\n ");
System.out.println("Please enter reference No.: ");
refNum = userInput.next();
rnLength = refNum.length();
}
while(!(refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z') && !(refNum.charAt(1) >= 'A') && !(refNum.charAt(1) <= 'Z'))
{
while(!(refNum.charAt(2) >= '0') && !(refNum.charAt(2) <= '9') && !(refNum.charAt(3) >= '0') && !(refNum.charAt(3) <= '9'))
{
while(!(refNum.charAt(4) >= '0') && !(refNum.charAt(4) <= '9') && !(refNum.charAt(5) >= 'A') && !(refNum.charAt(5) <= 'Z'))
{
System.out.println("Invalid reference number. Try again.\n ");
System.out.println("Please enter reference No.: ");
refNum = userInput.next();
}
}
}
答案 0 :(得分:0)
首先!(A >= B)
相当于(A < B)
。因此!(refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z')
相当于(refNum.charAt(0) < 'A') && (refNum.charAt(0) > 'Z')
。
如果您查看ASCII table,您会看到&#34;小于A且大于Z&#34;是相互排斥的条件。它们永远不会同时成立,因此while循环最终会简化为while(false)
答案 1 :(得分:0)
您的条件while(!refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z'))
始终为false,因为char不能同时小于'A'
且大于'Z'
。使用||
代替&&
,您就可以了。
我建议使用
Character.isLetter(refNum.charAt(0)) // returns true if the passed character is a letter
Character.isDigit(refNum.charAt(0)) // returns true, if the passed character is a digit.
更简单&amp;易于阅读。
答案 2 :(得分:0)
您的while
条件都错了。例如!(refNum.charAt(0) >= 'A') && !(refNum.charAt(0) <= 'Z')
检查某个字符是否低于A
且高于Z
,这是不可能的;你应该使用or
代替。
事实上,有一些很多方法可以改善这一点。这是我的版本
public class Testing_Code
{
static boolean inRange(char c, char first, char last) {
return (c >= first) && (c <= last);
}
public static void main(String[] args)
{
Scanner userInput = new Scanner (System.in);
String refNum;
System.out.println("Enter refNum: example - WE123A");
refNum = userInput.next();
while(refnum.length() != 6
|| !inRange(refnum.charAt(0), 'A', 'Z')
|| !inRange(refnum.charAt(1), 'A', 'Z')
|| !inRange(refnum.charAt(2), '0', '9')
|| !inRange(refnum.charAt(3), '0', '9')
|| !inRange(refnum.charAt(4), '0', '9')
|| !inRange(refnum.charAt(5), 'A', 'Z'))
{
System.out.println("Invalid reference number. Try again.\n ");
System.out.println("Please enter reference No.: ");
refNum = userInput.next();
rnLength = refNum.length();
}
}
}