簡體   English   中英

為信用卡生成一個隨機數

[英]generate a random number for a credit card

我嘗試使用此方法來生成一個16位數字的信用卡號,如果issuerSymbol等於ISSUER AMER EXPRESS,則該數字以4開頭。 如果issuerSymbol等於ISSUER VISA,則隨機數必須以3開頭,如果它是ISSUER MASTER CARD,則隨機數必須以5開頭。

 public Integer getIssuerCode(String issuerSymbol){
            int randomInteger = 0;
          Random   random = new Random();


    for(int i = 0; i < 5; i++) {
            randomInteger = random.nextInt();
         if (issuerSymbol.equals(ISSUER_AMER_EXPRESS)) {

         }

          else {
             System.out.println("error");
         }
         if(issuerSymbol.equals(ISSUER_VISA)){

         }
          else{
              System.out.println("error");
          }
           if (issuerSymbol.equals(ISSUER_MASTER_CARD)){

         }
           else{
                 System.out.println("error");
           } 
    }

     return randomInteger;
        }

我認為您是否有其他問題。 您需要了解,如果if不是true,它將進入else,應將代碼更改為if if else。

if (issuerSymbol.equals(ISSUER_AMER_EXPRESS)) {

} else if(issuerSymbol.equals(ISSUER_VISA)){

} else if (issuerSymbol.equals(ISSUER_MASTER_CARD)){

} else {
             System.out.println("error");
}

另一個建議的Random類包括nextInt(int)其(每Javadoc中)*返回偽隨機的,均勻分布int值介於0(含)和指定值(不包括),從該隨機數生成器的序列繪制。

randomInteger = 3 + random.nextInt() % 3; 

要么

randomInteger = 3 + random.nextInt(3); 

這將確保您randomInteger始終位於3或4或5中

用16位數字表示,您可以獲得的信用卡最大數字是5999999999999999,而int可以表示的最大數字是2 ^ 31-1或2,147,483,647,所以我建議改用BigInteger。 根據您計划使用randomInteger的方式,它可以是BigInteger或String。

由於您嘗試獲取16位數字,但第一個數字確定為3、4或5,這意味着您需要15個隨機整數。 您可以使用if-else if語句基於發布者符號設置randomInteger ,然后可以使用for循環來選擇15個隨機整數並將其附加到randomInteger。

//assuming randomInteger is already equal to 3, 4, or 5 
//and randomInteger is of type BigInteger
for(int i = 0; i < 15; i++)
{
  randomInteger = randomInteger.multiply(BigInteger.valueOf(10);
  randomInteger = randomInteger.add(BigInteger.valueOf(random.nextInt(10));
}

如果希望randomInteger為字符串,則只需將第一個數字連接為一個空字符串(“”),然后繼續連接一個隨機數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM