将int转换为arr。继续获取错误线程“main”中的异常java.util.InputMismatchException

时间:2018-02-18 02:14:18

标签: java arrays eclipse int

我正在编写一个程序来测试信用卡号的有效性。这是我到目前为止所写的内容,并且检查正确数量的第一个if语句可以正常工作,如果没有足够的数字,它将输出无效。第二个if语句不起作用,我不确定为什么。每当我输入一个满足两个if语句的数字时,我都会收到错误消息:

**线程“main”中的异常java.util.InputMismatchException:对于输入字符串:“44444444444444”

at java.util.Scanner.nextInt(Unknown Source)

at java.util.Scanner.nextInt(Unknown Source)

在Program1.main(Program1.java:9)**

不确定我是否完全错误地将int转换为数组的方式,或者它是否是小而愚蠢的东西。我没有很多Java经验。有人可以解释一下我做错了什么,或者是否有更好的方法来做我想要完成的事情?任何见解都会有所帮助。

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Enter the credit number: ");
    int creditNumber = input.nextInt();

    // Converts int to array.
    String temp = Integer.toString(creditNumber);
    int [] arr = new int[temp.length()];
    int counter = 0;
    for(int i = 0; i < temp.length(); i++) {
        arr[i] = temp.charAt(i) - '0';
        counter++;
    }

    // Checks for correct amount of numbers.
    if(!(counter >= 13 && counter <= 16)) {
        System.out.println("Invalid.");
        System.exit(0);
    }   

    // Checks for type of card.
    if((arr[0] != 4) || (arr[0] != 5) || (arr[0] != 6) || ((arr[0] != 3) && (arr[1] != 7))) {
        System.out.println("Invalid");
        System.exit(0);
    }
    else
        System.out.println("Valid");
        System.exit(0);

    input.close();
}

1 个答案:

答案 0 :(得分:2)

44444444444444是一个太大的数字,不适合整数。由于输入超出了整数范围,因此会出现输入不匹配异常。考虑使用long或bigint代替。我用了很长时间尝试了它并且工作正常。