我正在开发一个小“项目”,用于将一些数据保存在 HashMap 中,我想稍后在控制台中打印出来。 我几乎已经完成了整个代码,但我在控制台中给出它时遇到了问题...... 到目前为止我的代码是:
import java.util.HashMap;
import java.util.Scanner;
public class Passwordsaver` {
public static void main(String[] args) throws InterruptedException {
// declare the hashmap
HashMap<Integer, String> Password = new HashMap<>();
boolean loopAgain = true;
Scanner scan = new Scanner(System.in);
// loop while user not entering no
do {
// ask for account (page)
System.out.print("Enter Page:");
String page = scan.nextLine();
// ask for password
System.out.print("Enter Password");
String password = scan.nextLine();
// add the key value pair from user input to the hashmap
String oldVal = password + page;
if (oldVal!=null) {
System.out.println("The password for the page: " + page + " is "
+ password + " and will be overwritten if entered again");
}
// ask user to check if another entry is required
System.out.print("Enter another account (y/n)?");
String answer = scan.nextLine();
// condition to satisfy in order to loop again
loopAgain = (answer.equals("y") || answer.equals("Y"));
} while (loopAgain);
scan.close();
System.out.println("\n**********************************");
System.out.println("The following accounts are in database");
System.out.println(" account "+ " password");
for(int page:Password.keySet()){
System.out.println(" "+ Password +" "+Password.get(page));
}
System.out.println("\n**********************************");
}
}
除了最后一步之外一切正常...我怎样才能打印它? 是否还可以保存数据,以便以后我仍然可以更改 map ,而无需一直打开 Eclipse?
非常感谢!
最佳答案
您正在打印完整的 HashMap(密码),而不是每个条目的键。 看一下下面的循环:
for(int page:Password.keySet()){
System.out.println(" "+ page +" "+Password.get(page));
}
这里我们打印条目的键和值。
就性能而言,最好迭代 entrySet
,因此您无需额外的查找成本:
for(Map.Entry<Integer,String> entry:Password.entrySet()){
System.out.println(" "+ entry.getKey() +" " + entry.getValue());
}
编辑
此外,您忘记将页面/密码组合存储在 HashMap 中。添加
Password.put(page, password)
存储数据。
您还必须将 HashMap 的类型更改为 HashMap<String,String>
关于java - 控制台中的 HashMap 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59908020/