我一直在研究一个程序,该程序应该分析用户输入的信用卡号,包括有关其公司的信息,是否有效等等。
我的问题是我继续运行NoSuchElementException
,从我读过的内容看来,我的一个循环似乎继续运行,但我不知道在哪里或为什么。
import java.util.*;
public class CreditCard {
public static void main (String[] args) {
Scanner in = new Scanner (System.in);
long nums = 0;
int length;
System.out.print("Enter 15 or 16-digit credit card number: ");
long numsEntered = in.nextLong();
if(isValid(nums) == true) {
System.out.println(nums + " is valid.");
} else {
System.out.println(nums + " is invalid.");
}
}
public static boolean isValid (long cc_num) {
long numsEntered;
int total = sumOfOdd(cc_num) + sumOfEven(cc_num);
return (total % 10 == 0) && (prefixMatched(cc_num, 1) == true) &&
(getSize(cc_num)>=13) && (getSize(cc_num)<=16);
}
public static int sumOfEven(long number) {
int doubleEven = 0;
long place = 0;
while (number > 0) {
place = number % 100;
doubleEven += getDigit((int) (place / 10) * 2);
number = number / 100;
}
return doubleEven;
}
public static int sumOfOdd(long number) {
int odd = 0;
while (number <=9) {
odd += (int)(number % 10);
number = number % 100;
}
return odd;
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstNum = number % 10;
int secondNum = (int)(number / 10);
return firstNum + secondNum;
}
}
public static boolean prefixMatched(Long number, int d) {
if((getPrefix(number, d) == 3) || (getPrefix(number, d) == 4) || (getPrefix(number, d) == 5)) {
if(getPrefix(number, d) == 3) {
System.out.println("Visa");
} else if (getPrefix(number, d) == 3) {
System.out.println("Amex");
} else if (getPrefix(number, d) == 5) {
System.out.println("Master Card");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d >0) {
d = d/10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if(getSize(number) < k) {
return number;
} else {
int size = (int)getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
}
我继续得到的确切错误是:
Enter 15 or 16-digit credit card number: Exception in thread "main"
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextLong(Scanner.java:2222)
at java.util.Scanner.nextLong(Scanner.java:2182)
at CreditCard.main(CreditCard.java:11)
答案 0 :(得分:0)
好吧,你用num
调用isValid。您是不是应该使用numsEntered
来调用isValid?