Java新手:有没有更好的方法来编写这个简单的代码

时间:2012-05-14 15:55:57

标签: java

private void addMember() {
    while (true) {
        String mNum = readLine("Please enter a membership number: ");
        if (mNum == null) break;
        Integer mNumAsInteger = Integer.parseInt(mNum);
        String mName = readLine("Please enter the member's name: ");
        members.put(mNumAsInteger, mName);
    }
}

private Map<Integer, String> members = new HashMap<Integer, String>();

代码的目的是在用户输入空白输入之前不断添加成员。

有没有办法将第一行更改为

Integer mNum = readInt("Please enter a membership number: ");

以某种方式检测到空白输入?

3 个答案:

答案 0 :(得分:1)

您可以使用Scanner,它提供了一个更简单的API来从流中读取。

private static void addMember() {
    Scanner sc = new Scanner(System.in).useDelimiter("\n");
    while (true) {
        try {
            System.out.println("Please enter a membership number: ");
            int mNum = sc.nextInt();
            System.out.println("Please enter the member's name: ");
            String mName = sc.next();
            members.put(mNum, mName);
        } catch (Exception e) {
            break;
        }
    }
}

http://ideone.com/jhN3j

答案 1 :(得分:0)

不确定是否最好,但也许您正在寻找:

try{
Integer mNum = Integer.parseInt(readLine("Please enter a membership number: "));
}catch (NumberFormatException e){
 System.out.println("Error parsing membership number");
}

答案 2 :(得分:0)