我正在尝试使程序根据卡号的第一位数字在屏幕上打印卡类型。该程序可以正常编译并运行,但是不会将卡类型声明显示在屏幕上。我敢肯定这只是一个简单的修复方法,但是我花了几个小时试图找出可能的结果。我在这里想念什么?
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;
}
}
最佳答案
charAt
返回一个char
,您正在将其与它的面值表示的int进行比较。即,您应该使用4
,5
和6
而不是'4'
,'5'
和'6'
。另外,请注意,“ 37”是两个字符,因此您不能只求第一个字符。相反,您可以使用String.startsWith(String)
和一系列if-else条件:
if (cNum.startsWith("4")) {
System.out.println ( "The card is a Visa" );
} else if (cNum.startsWith("5")) {
System.out.println ( "The card is a MasterCard" );
} else if (cNum.startsWith("6")) {
System.out.println ( "The card is a Discover Card" );
} else if (cNum.startsWith("37")) {
System.out.println ( "The card is an American Express Card" );
}
关于java - 案例陈述代码不显示在屏幕上,但符合要求且没有错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46617904/