【发布时间】: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();
}
【问题讨论】: