【发布时间】:2020-02-02 22:44:54
【问题描述】:
我正在用 Hackerrank 做地图练习。目标是输入要输入的条目总数,然后输入键和值,直到达到条目数。还要寻找密钥是否存在。但是,我的代码运行不正常。即使我在扫描仪输入之前打印出“请输入姓名以查找电话号码:”,但扫描仪输入首先读取。这是为什么呢?
Scanner scanner = new Scanner(System.in);
Map<String, Integer> phone = new HashMap<>();
System.out.print("Please enter total number of entries: ");
int n = scanner.nextInt();
scanner.nextLine();
for(int x=0;x<n;x++) {
System.out.print("Please enter name: ");
String name = scanner.nextLine();
System.out.print("Please enter phone number: ");
int num = scanner.nextInt();
scanner.nextLine();
phone.put(name,num);
}
while(scanner.hasNext()) {
System.out.println("Please enter name to find phone number: "); //the problem is here
String findName = scanner.nextLine(); // this will read first before above line
if(phone.containsKey(findName)) {
System.out.println(findName + "=" + phone.get(findName));
} else {
System.out.println("not found");
}
}
【问题讨论】:
标签: java dictionary java.util.scanner