因此,我的程序应该采用用于 Visa 或 MasterCard 的 16 位数字的附加形式。但是,当我运行它时,程序会读取一个空格作为输入的结尾。例如:如果我输入 1234 5678 9012 3444,程序只会在我输入空格之前添加数字的总和。然后,如果我输入没有空格的整个字符串,它会不断给我错误代码。我在这里做错了什么?
import java.util.Scanner;
public class assignment4
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int sum = 0, number, modulo;
String cardBrand;
System.out.print("Visa or MasterCard? ");
cardBrand = in.nextLine();
System.out.print("Please enter your 16 digit credit card number (no spaces): ");
number = in.nextInt();
while (number > 0)
{
int digit = number % 10;
sum = sum + digit;
number = number/10;
}
modulo = (sum % 10);
if (cardBrand.equals("Visa"))
{
if (modulo == 0)
{
System.out.println("This is a valid Visa card. Good job.");
}
else
{
System.out.println("This is an invalid Visa card number.");
}
}
else if (cardBrand.equals("MasterCard"))
{
if (modulo == 1)
{
System.out.println("This is a valid MasterCard.");
}
else
{
System.out.print("This is an invalid MasterCard card number.");
}
}
}
}