我需要爲使用java的類創建一個upc代碼驗證器。 upc驗證部分完美工作,但我需要一種方法來只接受一個12位數字輸入。如何驗證輸入只接受12位數字的輸入?
任何幫助,將不勝感激。
謝謝! 我的代碼看起來是這樣的:
public class UPC {
public static void main(String[] args) {
// get input number
Scanner Keyboard = new Scanner(System.in);
System.out.print("Enter a 12-digit barcode: "); //prompt user for input
long input = Keyboard.nextLong();
long number = input;
int d11 = (int) (number % 10);
number /= 10;
int d10 = (int) (number % 10);
number /= 10;
int d9 = (int) (number % 10);
number /= 10;
int d8 = (int) (number % 10);
number /= 10;
int d7 = (int) (number % 10);
number /= 10;
int d6 = (int) (number % 10);
number /= 10;
int d5 = (int) (number % 10);
number /= 10;
int d4 = (int) (number % 10);
number /= 10;
int d3 = (int) (number % 10);
number /= 10;
int d2 = (int) (number % 10);
number /= 10;
int d1 = (int) (number % 10);
number /= 10;
int d0 = (int) (number % 10);
int m = d1 + d3 + d5 + d7 + d9;
int n = d0 + d2 + d4 + d6 + d8 + d10;
int r = (10 - ((m + 3*n) % 10)) % 10;
System.out.println("Anatomy of Your UPC Barcode");
System.out.println("====================================");
System.out.println(" UPC: " + input);
System.out.println(" NSC: " + d0);
System.out.println(" Manufacturer Number: " + d1 + d2 + d3 + d4 + d5);
System.out.println(" Product Code: " + d6 + d7 + d8 + d9 + d10);
System.out.println(" Family Code: " + d6 + d7 + d8);
System.out.println(" Value Code: " + d9 + d10);
System.out.println(" Scanned Check Digit: " + d10);
System.out.println("Calculated Check Digit: " + d11);
if (r == d11) {
// is a upc code
System.out.println(" Validity status: valid");
}
else {
// not a upc code
System.out.println(" Validity status: invalid");
}
}
}
'if(str.matches(「\\ d {12}」))' –
編輯我的帖子,不確定在哪裏陳述你剛纔的陳述。 –