我的Java代码中的InputMismatchException

时间:2017-10-24 15:36:56

标签: java hashmap

以下代码尝试读取memberid和用户选择的成员资格。 user输入-1表示程序结束。系统现在将显示总和并退出。我希望得到下面的错误,这很奇怪:

package task2;

import java.util.HashMap;
import java.util.Scanner;

public class Task2 {
    // i will make scanner class object accessible to current class

    static Scanner read = new Scanner(System.in);
    static HashMap<String, Double> storeMembers = new HashMap<>();
    static int choice;
    static String membershipID;
    static double amount;
    static double total;

    public static void displaySum() {
        for (Double sum : storeMembers.values()) {
            amount += sum;
        }
    }

    public static void main(String[] args) {
        System.out.println("Enter  MembershipID eg: JPU123D");
        System.out.println("For Standard Membership, Enter:  1");
        System.out.println("For Concession Membership,Enter: 2");

        while (read.hasNext()) {
            choice = read.nextInt();
            membershipID = read.nextLine();
            if (choice == 1) {

                if (storeMembers.containsKey(membershipID)) {
                    amount = Membership.standardMemberAnnualfee();
                    storeMembers.put(membershipID, amount);
                }
            } else {
                amount = Membership.standardMemberAnnualfee() + Membership.standardMemberjoinfee();
                storeMembers.put(membershipID, amount);
            }
            if (choice == -1) {
                System.out.println("Now closing the application!");
                System.out.println("Total fees:");
                displaySum();
                System.exit(1);
            }
        }// end while
    }
}

错误说:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at task2.Task2.main(Task2.java:28)
Java Result: 1
BUILD SUCCESSFUL (total time: 8 seconds)

任何人都可以告诉我我做错了什么,因为我相信我的扫描仪对象正在读取正确的输入类型。

0 个答案:

没有答案