我正在使用信用卡验证程序,但我还希望实现识别其第一个数字值输入的信用卡类型的代码。 如何根据第一个数值识别字符串?
import java.util.Scanner;
public class parking_garage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter a credit card cardnumber as a long integer
System.out.print("Enter a credit card cardnumber as a long integer: ");
long cardnumber = input.nextLong();
System.out.println(
cardnumber + " is " + (isValid(cardnumber) ? "valid" : "invalid"));
}
/** Return true if the card cardnumber is valid */
public static boolean isValid(long cardnumber) {
boolean valid =
(getSize(cardnumber) >= 13 && getSize(cardnumber) <= 16) &&
(prefixMatched(cardnumber, 4) || prefixMatched(cardnumber, 5) ||
prefixMatched(cardnumber, 37) || prefixMatched(cardnumber, 6)) &&
((sumOfDoubleEvenPlace(cardnumber) + sumOfOddPlace(cardnumber)) % 10 == 0);
return valid;
}
/** Get the result from Step 2 */
public static int sumOfDoubleEvenPlace(long cardnumber) {
int sum = 0;
String num = cardnumber + "";
for (int i = getSize(cardnumber) - 2; i >= 0; i -= 2) {
sum += getDigit(Integer.parseInt(num.charAt(i) + "") * 2);
}
return sum;
}
/** Return this cardnumber if it is a single digit, otherwise,
* return the sum of the two digits */
public static int getDigit(int cardnumber) {
if (cardnumber < 9)
return cardnumber;
else
return cardnumber / 10 + cardnumber % 10;
}
/** Return sum of odd-place digits in cardnumber */
public static int sumOfOddPlace(long cardnumber) {
int sum = 0;
String num = cardnumber + "";
for (int i = getSize(cardnumber) - 1; i >= 0; i -= 2) {
sum += Integer.parseInt(num.charAt(i) + "");
}
return sum;
}
/** Return true if the digit d is a prefix for cardnumber */
public static boolean prefixMatched(long cardnumber, int d) {
return getPrefix(cardnumber, getSize(d)) == d;
}
/** Return the cardnumber of digits in d */
public static int getSize(long d) {
String num = d + "";
return num.length(); }
/** Return the first k cardnumber of digits from cardnumber. If the
* cardnumber of digits in cardnumber is less than k, return cardnumber. */
public static long getPrefix(long cardnumber, int k) {
if (getSize(cardnumber) > k) {
String num = cardnumber + "";
return Long.parseLong(num.substring(0, k));
}
return cardnumber;
}
答案 0 :(得分:0)
你可以做这样的事情
public boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?");
}
public void randomName(String str){
for (int i =0 ;i<str.Length;i++){
if(isNumeric(str.charAt(i)+"")){
//Do THING
break;
}
}
}
这将循环遍历字符串中的所有值,一旦找到一个数字//Do THING
将运行,这就是你应该放置代码的地方
答案 1 :(得分:0)
信用卡以某些号码开头,如
VISA -4
MASTERCARD -5
AMEX - 3
DISCOVER -6
发布我的答案后,我在github上找到了这个。 https://gist.github.com/gabrielbauman/f3db7ce8ae7828fa05b3