我的Java代码无法正常工作。在要求用户输入R或P之后,我一直收到此错误消息。这是什么意思?我该如何解决?
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at PhoneBill3.main(PhoneBill3.java:17)
import java.util.Scanner;
public class PhoneBill3
{
public static void main (String [] args)
{
double acctNum;
int svcType=0;
int dtmin=0;
int ntmin=0;
int dtFree=50;
int ntFree=100;
int minUsed=0;
Scanner scan= new Scanner (System.in);
System.out.print ("Please enter your account number: ");
acctNum=scan.nextDouble();
System.out.println ("Service type (R/P): ");
svcType = scan.nextInt ();
System.out.print("You entered " +svcType);
//using switch to decide what to do with user input
switch (svcType)
{
case 'R':
//if case R is entered, this should prompt the user to enter
total minutes used and determin the cost of the Regular bill
System.out.println ("Total minutes used: ");
minUsed=scan.nextInt ();
if (minUsed<50){
System.out.println ("Account number: " + acctNum);
System.out.println ("Account type: Regular");
System.out.println ("Total minutes: " + minUsed);
System.out.println ("Amount due: $15.00");}
else{
System.out.println ("Account number: " + acctNum);
System.out.println ("Account type: Regular");
System.out.println ("Total minutes: " + minUsed);
System.out.println ("Amount due: $"+ 15 + (minUsed-
50)*.2);}
break;
case 'P':
//if case P is entered, this should prompt the user to enter
day time and night time minutes used
System.out.println ("Number of daytime minutes used: ");
dtmin=scan.nextInt ();
double dtTtlDue=0.00;
System.out.println ("Number of nighttime minutes used: ");
ntmin=scan.nextInt ();
double ntTtlDue=0.00;
dtTtlDue= (dtmin-dtFree)*.2;
ntTtlDue= ((ntmin-ntFree)*.1);
System.out.println ("Account number: " + acctNum);
System.out.println ("Account type: Premium");
System.out.println ("Daytime Min: "+ dtmin);
System.out.println ("Nighttime Minutes: " + ntmin);
System.out.println ("Amount due: $" + 25.00+ dtTtlDue +
ntTtlDue);
break;
default:
System.out.println ("That is not a valid service type.
Enter R for regular or P for premium.");
break;
}
}
}
我需要最终产品打印帐号,服务类型,并根据服务类型,使用的分钟数或白天和夜间的分钟数来打印。然后根据答案打印总账单。
答案 0 :(得分:0)
之所以发生这种情况,是因为您将R & P
的输入读为int
。应将其读为String
请更改
System.out.println ("Service type (R/P): ");
svcType = scan.nextInt ();
到
System.out.println ("Service type (R/P): ");
svcType = scan.next ().charAt(0);
答案 1 :(得分:0)
您要用户输入一个String值(长度为1),并尝试将其分配给一个int变量(svcType)。您需要进行2项更改:
1)将svcType变量的类型更改为char:
char svcType = '?';
2)仅从用户输入中提取输入的第一个字符:
scan.next().charAt(0);
您还可以toUpperCase()
输入以允许使用小写的“ r”或“ s”:
scan.next().toUpperCase().charAt(0);