[英]retrieving character from string.length() , using a FOR statement
我正在使用for語句和字符串實現Luhn算法。
我的問題是,“j”是否在字符串的位置(數字)中分配了字符的值,或者是否在字符串長度中分配了其數字位置的值?
謝謝
*如果我不應該直接將代碼粘貼到此,請道歉
*編輯:我很確定它實際上並沒有檢索字符,而只是它在字符串中的數字位置,研究char方法
if (card.length() < 13 || card.length() > 16)
{
JOptionPane.showMessageDialog(null, "Invalid credit card number");
card = JOptionPane.showInputDialog("Please enter the credit card number.");
num = Long.parseLong(card);
}
for (int j = 0; j < card.length(); j++) {
sum = sum + j*2;
if ( j%2 != 0 ) {
product = j * 1;
sum += product;
}
else {
product = j * 2;
}
if (product > 9) {
product -= 9;
sum += product;
}
}
你有一個for
聲明
for (int j = 0; j < card.length(); j++) {
它聲明和初始化變量j
與值0它增加的值j
由一個與所述每個迭代j++
表達。 當j
的值小於card.length()
的值時,它card.length()
。
這是職位的數量。 card.length()
返回一個int,因此j
將獲得該值(“position”)。
請嘗試以下示例來查看差異:
String s = "Hello World";
for (int i = 0; i < s.length(); i++){
System.out.println(" Value of i: " + i);
System.out.println(" Value of i in s: " + s.charAt(i));
System.out.println("Value of i as char: " + (char)i);
System.out.println("---");
}
前3次迭代:
Value of i: 0
Value of i in s: H
Value of i as char: NUL**
---
Value of i: 1
Value of i in s: e
Value of i as char: SOH**
---
Value of i: 2
Value of i in s: l
Value of i as char: STX**
** char值不可見,您可以在這里查找: http : //ascii.cl/如果i
達到33 - 它將變得可讀,從開始!
。
在你的代碼中,“j”只是位置,並且將獲得值:0,1,2,3,4 ....直到字符串長度。
您想要的是該位置的字符所代表的數字,因此字符“0”(其值為“30”)需要轉換為值為+ 0的整數,字符“9”(x'39')需要要轉換為整數值+9。
你可以這樣做:
int cval = Integer.parseInt(card.charAt(j));
或快速而骯臟:
int cval = card.charAt(j) - 30;
當你給它一個非數字字符時,第一個方法將拋出異常,第二個方法將從它得到的任何東西中減去30(這個代碼是一個非常高值的unicode字符)所以只有在你完全確定字符串時才使用這個方法將僅包含ASCII字符0123456789。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.