【发布时间】:2020-10-14 15:15:18
【问题描述】:
我正在使用 java 为类编写程序。我已经编写了第一部分代码,但我无法弄清楚我做错了什么。当我运行该程序时,它让我输入一个卡号,但它给了我一个错误。我的教授说这是因为对于这个程序,卡号太长而无法存储为 int。我明白这一点,所以它被存储在一个字符串中。但我仍然遇到错误。请帮忙。
package creditCard;
import java.util.Scanner;
public class Card {
public static void main(String[] args) {
//Set up a scanner
Scanner in = new Scanner(System.in);
//Set up a boolean named creditCard and set it to false
boolean validCreditCard = false;
//Loop while not a valid credit card
while (!validCreditCard) {
//Prompt the user for a potential credit card number
System.out.print("Please enter a card number: ");
//Get the credit card number as a String - store in potentialCCN
String potentialCCN = in.next();
//Use Luhn to validate a credit card
//Store the digit as an int for later use in lastDigit
int lastDigit = Integer.parseInt(potentialCCN);
//Test then comment out! -check the last digit
System.out.println(lastDigit+"Check the last digit");
//Remove the last digit from potentialCCN and store in potentialCCN using String's substring
potentialCCN = potentialCCN.substring(15);
//Test then comment out! - check potential credit card number
System.out.println(potentialCCN);
}
}
}
【问题讨论】:
-
你得到什么错误?你输入了哪个号码?
-
信用卡号一般为15-16位,但最长可达19位。一个
int只能存储9-10位数字,所以parseInt()会抛出NumberFormatException,因为该值超出了int支持的范围。您也许可以使用long或BigInteger,但为什么呢?您永远不会将信用卡号视为数值,即使它全是数字,所以请将其保留为String。 -
我认为问题可能出在
int lastDigit = Integer.parseInt(potentialCCN);,这里我假设(由于变量名)您想选择“最后一位”,但parseInt()正在解析整个字符串。我同意@Andreas,您可以使用 String 并为您的支票选择所需的数字。 -
@Andreas 看来 OP 想要提取/解析 Luhn 算法的最后一位数字
标签: java