【问题标题】:Converting int to arr. Keep getting error Exception in thread "main" java.util.InputMismatchException将 int 转换为 arr。在线程“main”java.util.InputMismatchException中不断收到错误异常
【发布时间】:2018-02-18 02:14:17
【问题描述】:

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

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

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

在 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();
}

【问题讨论】:

    标签: java arrays eclipse int


    【解决方案1】:

    44444444444444 数字太大,无法放入整数。由于您的输入超出了整数范围,因此您会收到输入不匹配异常。考虑改用 long 或 bigint。我试了很长时间,效果很好。

    【讨论】:

    • 谢谢,消除了错误信息。第二个 if 语句仍然无法正常工作。如果没有满足这些要求,它应该打印 Invalid,这意味着它只必须满足其中一个。但是它只打印无效。关于如何解决这个问题的任何想法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    相关资源
    最近更新 更多