java - 我不明白我做错了什么。如何将 int 存储在 String 中而不出错?
问题描述
我正在使用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);
}
}
}
解决方案
你的问题是 parseInt。您可以使用 BigInteger 解决这个问题,例如
BigInteger bi = new BigInteger(potentialCCN);
或者您可以使用正则表达式来验证potentialCCN 是一个16 位数字,例如
^[0-9]{16,16}$
推荐阅读
- android - 如何制作可在每个屏幕手机中使用的响应式 Android 应用程序?
- android - 无法解决:com.google.android.gms:play-services:16.0.1
- python - 在矢量化操作中调用 numpy 函数会影响性能吗?
- python - 将 html 代码从“字符串”复制到下一个“字符串”
- c++ - 防止调用某些 std 函数
- spring-mvc - 请帮助解释 Lombok 的 @AllArgsConstructor 和 spring 的 @RestController 的奇怪组合
- python-3.x - 如何修复错误:命令错误退出状态 1:python setup.py egg_info 安装 geograpy 包
- sql-server - 从 SQL Server Management Studio 连接到数据库服务器时出错
- powershell - 缺少双面 WIA 扫描属性
- spring-boot - 如何使用 Spring Boot jmsListener 为失败的消息配置 DLQ?