Question about InputMismatchException while using Scanner

后端 未结 5 1774
一整个雨季
一整个雨季 2021-01-23 08:50

The question :

Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, in

5条回答
  •  一整个雨季
    2021-01-23 09:45

    You may want to include the content of Account.in to provide more information, but here are some comments:

    Naming conventions

    Variables: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.

    This means that by convention, the variable names should be upper/lower-cased like accountNum, beginningBalance, numberOfDeposits, etc.

    It should also be mentioned that the way you're placing your curly braces are highly unconventional. It may be a good idea for you to learn good coding style.


    This part is also highly inconsistent:

    int TransactionType; // declared as int
    //...
    TransactionType=inFile.nextInt(); // read as int
    //...
    switch (TransactionType)
       case '1': // used as ... char? ASCII '1' = 49
    

    I'm 99% certain that you really need to switch on case 1:, case 2:, case 3: instead.


    You may also want to print the ending balance AFTER you processed the transaction. Right now, you'll always print the same numbers for beginning and ending balance.

    It may also benefit you to know that Java has "compound assignment" operators that would make your code a lot more readable. You probably need not concern yourself with the exact semantics right now, but basically instead of this:

                BeginningBalance = BeginningBalance
                        + TransactionAmount;
    
                BeginningBalance = BeginningBalance
                        - TransactionAmount;
    

    You can instead write:

    beginningBalance += transactionAmount;
    
    beginningBalance -= transactionAmount;
    

    Finally, one last comment about the InputMismatchException: others have already explained to you what this means. My best guess right now is that your problem is caused by this:

    Input file: customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount

    vs:

               TransactionAmount=inFile.nextDouble();
               TransactionType=inFile.nextInt();
    

    I need to see Account.in to confirm, but I suspect that the int transaction type appears before the double transaction amount, just like the problem statement says. Your code reads them in the opposite order.

    This would attempt to read the int as nextDouble(), which is okay, but the double as nextInt() would throw InputMismatchException.

提交回复
热议问题