gpt4 book ai didi

java - Java 新手 : Is there a better way to write this simple code

转载 作者:行者123 更新时间:2023-12-01 15:23:02 24 4
gpt4 key购买 nike

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: ");

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

最佳答案

您可以使用 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

关于java - Java 新手 : Is there a better way to write this simple code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10586825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com