首页 > 解决方案 > 我不明白我做错了什么。如何将 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);
            
        }

    }

}

标签: java

解决方案


你的问题是 parseInt。您可以使用 BigInteger 解决这个问题,例如

BigInteger bi = new BigInteger(potentialCCN);

或者您可以使用正则表达式来验证potentialCCN 是一个16 位数字,例如

^[0-9]{16,16}$


推荐阅读