2016-10-09 51 views
-2

試圖編寫一個程序,該程序採用奇數索引處的所有數字並且應該被添加以形成總和。 實施例:如果信用卡號碼是43589795,則形成的總和3 + 8 + 7 + 5是23.從用戶輸入的號碼中抓取單個號碼並檢查它是奇數還是偶數索引

然後雙每個是在偶數索引,並添加所得的所有數字數字數字的總和。 例如:上面的數字,加倍數字產生8 10 18 18.添加這些值中的所有數字產生8 + 1 + 0 + 1 + 8 + 1 + 8爲27,所以最終總和爲23 + 27如果最後一筆金額的最後一位是0,那麼信用卡號碼是有效的。在我們的例子中,最後一位50是0,所以這個數字是有效的。

我將不勝感激一些幫助,我試圖更好地理解循環,並使用Character.isDigit。謝謝!

import java.util.Scanner; 
public class CreditCard { 
    public static void main(String args[]) { 
     Scanner scan = new Scanner(System.in); 

     final String CREDIT_CARD = "[0-9]{8}"; 
     int length = 8; 
     String num, response; 
     char ch1, ch2; 

     do { 
      do { 
      System.out.println("Please enter a 8 digit credit cardnumber");//validating that the user entered 8 digits. 
      num = scan.next(); 
       ch1 = num.charAt(0); 
      } while (!num.matches(CREDIT_CARD)); 

     for (int i = 0; i < CREDIT_CARD.length(); i++){ //for loop for checking if number is at odd or even index? 
      Character.isDigit(ch1); //Trying to use Character.isDigit to validate whether it is at odd or even index? 
      if (ch1 % 2== 1){ 

      } 
     } 





      System.out.println("Would you like to enter a different card?"); 
      response = scan.next(); 
    }while (response.equals("yes")); //Do while loop asking if user wants to enter another card. 

     System.out.println("Goodbye!"); 


    } 
} 

回答

-2

請找到解決辦法。在這裏,我們首先檢查卡號中的字符是否是數字。如果沒有,我們正在打破循環和打印無效。如果數字的有效性比我們根據索引執行操作有效。當位置是奇數時,我們再次計算總數字的數字值。

  int sum = 0; 
      Boolean isValidCard = true; 
      for (int i = 0; i < num.length(); i++) { 
       ch1 = num.charAt(i); 
       if (Character.isDigit(ch1)) { 
        if (i % 2 == 1) { 
         sum += ((int) ch1 - 48); 
        } else { 
         int temp = (2 * ((int) ch1 - 48)); 
         while (temp > 0) { 
          sum += temp % 10; 
          temp = temp/10; 
         } 
        } 
       } else { 
        isValidCard = false; 
        break; 
       } 
      } 
      if (!isValidCard) { 
       System.out.println("CC Invalid"); 
      } else if (sum % 10 == 0) { 
       System.out.println("CC is valid"); 
      } 
+0

花花公子你真的不熟嗎?沒有提供原因的向下投票? – cody123

相關問題