我试图让程序根据卡号的第一位数字在屏幕上打印卡片类型。该程序编译正常并运行,但它不会将卡类型语句放在屏幕上。我确信这只是一个简单的修复,但我花了几个小时试图发现它可能是什么。我在这里缺少什么?
public static void main (String [] args ) {
System.out.println ( "Please enter your credit card number without spaces." );
Scanner keyIn = new Scanner ( System.in );
long ccNum = keyIn.nextLong ();
String cNum = ccNum + "";
switch ( cNum.charAt ( 0 ) )
{
case 4:
System.out.println ( "The card is a Visa" );
break;
case 5:
System.out.println ( "The card is a MasterCard" );
break;
case 6:
System.out.println ( "The card is a Discover Card" );
break;
case 37:
System.out.println ( "The card is an American Express Card" );
break;
}
}
答案 0 :(得分:1)
public static void main (String [] args ) {
System.out.println ( "Please enter your credit card number without spaces." );
Scanner keyIn = new Scanner ( System.in );
long ccNum = keyIn.nextLong ();
String cNum = ccNum + "";
switch ( Character.getNumericValue(cNum.charAt ( 0 )) )
{
case 4:
System.out.println ( "The card is a Visa" );
break;
case 5:
System.out.println ( "The card is a MasterCard" );
break;
case 6:
System.out.println ( "The card is a Discover Card" );
break;
case 37:
System.out.println ( "The card is an American Express Card" );
break;
}
}
返回charAt
,您将其与其面值所代表的int进行比较。即,不应使用char
,4
和5
,而应使用6
,'4'
和'5'
。另请注意,“37”是两个字符,因此您不能只评估第一个字符。相反,您可以使用String.startsWith(String)
和一系列if-else条件:
'6'
答案 1 :(得分:1)
您正在将char与整数进行比较。
使用switch语句查看解决方案:
public static void main (String [] args ) {
System.out.println("Please enter your credit card number without spaces.");
final Scanner keyIn = new Scanner(System.in);
long ccNum = 0L;
if (keyIn.hasNext()) {
ccNum = keyIn.nextLong();
}
final String cNum = "" + ccNum;
int firstDigits = Integer.parseInt(cNum.substring(0, 2));
if (firstDigits > 37) {
firstDigits /= 10;
}
switch(firstDigits) {
case 4: {
System.out.println("The card is a Visa");
break;
}
case 5: {
System.out.println("The card is a MasterCard");
break;
}
case 6: {
System.out.println("The card is a Discover Card");
break;
}
case 37: {
System.out.println("The card is an American Express Card");
break;
}
default: {
System.out.println("Incorrect card number");
}
}
}
答案 2 :(得分:0)
如果您想将卡号与您的案例进行比较。您需要将var elemetsWithClassClose = document.getElementsByClassName("close");
var contactSpan = elemetsWithClassClose[0];
转换为cNum.charAt ( 0 ) )
。但是案例37 ??
int