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: ");
以某种方式检测到空白输入?
答案 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;
}
}
}
答案 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)