如何在限制条件小于或等于给定限制的情况下打印HashMap中的数据库?

huangapple go评论77阅读模式
英文:

How to print a database in HashMap that is less than or equals to the given limit?

问题

我正在尝试使用`HashMap`创建一个包含恐龙名称和重量的数据库我希望在`printMatchingDinos()`方法中设置一个重量限制只有重量小于等于限制的恐龙才会被打印

public class DinoDatabase {
    private HashMap<String, Integer> listOfDinos = new HashMap<>();
    private String name;
    private int weight;

    public DinoDatabase() {
        Map<String, Integer> listOfDinos = new HashMap<String, Integer>();
        this.name = name; // 恐龙的名称
        this.weight = weight; // 恐龙的重量
    }

    // 将恐龙添加到数据库
    public void addDino(String name, int weight) {
        if (!listOfDinos.containsKey(name)) {
            listOfDinos.put(name, weight);
            System.out.println(name + "已添加。重量:" + weight + "kg");
        }
        else {
            System.out.println(name + "无法添加。它已经在数据库中了!");
        }
    }

    // 打印重量小于等于限制的恐龙
    public void printMatchingDinos(int limit) {
        if (weight > limit) {
            listOfDinos.remove(name, weight);
            for (String name : listOfDinos.keySet()) {
                System.out.println(listOfDinos.get(name));
            }
        }
        else {
            System.out.println("没有符合条件的恐龙");
        }
    }

    public static void main(String[] args) {
        DinoDatabase db = new DinoDatabase();
        db.addDino("Dravidosaurus", 907);
        db.addDino("Eouplocephalus", 3175);
        db.addDino("Tyrex", 1000);
        db.printMatchingDinos(1000);
    }
}

/* 输出:
Dravidosaurus已添加。重量:907kg
Eouplocephalus已添加。重量:3175kg
Tyrex已添加。重量:1000kg
没有符合条件的恐龙 */
英文:

I am trying to make a database with HashMap that contains the name and weight of Dinos. I want to set a weight limit on printMatchingDinos() method, such that only Dinos with weight less than or equals to the limit will be printed.

public class DinoDatabase {
private HashMap&lt;String, Integer&gt; listOfDinos = new HashMap&lt;&gt;();
private String name;
private int weight;
public DinoDatabase() {
Map&lt;String, Integer&gt; listOfDinos = new HashMap&lt;String, Integer&gt;();
this.name = name; // Dino&#39;s name
this.weight = weight; // Dino&#39;s weight
}
// Add dino to the database
public void addDino(String name, int weight) {
if (!listOfDinos.containsKey(name)) {
listOfDinos.put(name, weight);
System.out.println(name + &quot; added. Weight: &quot; + weight + &quot;kg&quot;);
}
else {
System.out.println(name + &quot; cannot be added. It is already in the database!&quot;);
}
}
// Print Dino which has a weight less than or equals to the limit
public void printMatchingDinos(int limit) {
if (weight &gt; limit) {
listOfDinos.remove(name, weight);
for (String name : listOfDinos.keySet()) {
System.out.println(listOfDinos.get(name));
}
}
else {
System.out.println(&quot;No Dino with given standard&quot;);
}
}
public static void main(String[] args) {
DinoDatabase db = new DinoDatabase();
db.addDino(&quot;Dravidosaurus&quot;, 907);
db.addDino(&quot;Eouplocephalus&quot;, 3175);
db.addDino(&quot;Tyrex&quot;, 1000);
db.printMatchingDinos(1000);
}
}
/* Output:
Dravidosaurus added. Weight: 907kg
Eouplocephalus added. Weight: 3175kg
Tyrex added. Weight: 1000kg
No Dino with given standard */

The expected output is

Dravidosaurus added. Weight: 907kg
Tyrex added. Weight: 1000kg

答案1

得分: 1

你似乎对这个类应该表示什么有些困惑。

你的类既有一个 name 字段又有一个 weight 字段,所以显然,一个 DinoDatabase 实例代表着 一个恐龙。然而,它还有一个将名称映射到重量的映射,因此它还代表了恐龙数据库的概念。

这是没有意义的。

你可能应该在这里使用两个类:public class Dino { String name; int weight; }public class DinoDatabase { Map<String, Dino> dinos; }。混在一起,这毫无意义,会让你感到困惑。例如,在你的构造函数中,你写了 this.name = name;,这根本什么都没做,它是将名称字段赋值给了自己。它只在有一个名为 name 的参数时才有意义。你甚至可以不创建任何 Dino 类,而只使用一个 Map<String, Integer> 来存储你的恐龙,但这意味着你只能存储恐龙的重量,不能方便地添加更多的属性,比如它们生存的时代,或者它们是否能飞行。

鉴于你在使用哈希映射,你无法在这里应用任何数据库智能;除非条件是:“名称恰好等于这个字符串”,否则找到所有与某个条件匹配的恐龙的唯一方法是遍历整个映射并返回所有匹配的条目。实际的数据库更智能,你可以添加一个索引,这样即使你有数百万只恐龙,这些查询也可以很快,但这涉及到比这段代码中正在进行的操作复杂得多的编程概念。我认为这个练习的目的只是简单地编写它,遍历 每一只 恐龙,只返回匹配的恐龙。这意味着你需要创建一个 ArrayList 对象(或者是你选择的其他集合),遍历并仅添加匹配的恐龙,然后返回该集合。

英文:

You seem rather confused on what this class is supposed to represent.

Your class has both a name and weight field, so, apparently, a DinoDatabase instance represents a single dinosaur. Yet, it also has a map that maps names to weights, so, it also represents the concept of a dino database.

That doesn't make sense.

You should probably have two classes here: public class Dino {String name; int weight; } and public class DinoDatabase { Map&lt;String, Dino&gt; dinos; }. Smushed together, that makes no sense and is confusing you a lot. For example, in your constructor, you write this.name = name; which does nothing whatsoever, it's assigning the name field to itself. It only makes sense if there is a parameter named name. You could get away with making no Dino class at all and sticking with a Map&lt;String, Integer&gt; for your dinos, but it does mean you're committed to only storing the weight of dinos and you can't conveniently add more properties, such as which era they were alive in, or whether they could fly or not.

Given that you're using a hashmap, there is no DB smarts you can apply here; the only way to find all dinos that match a certain condition, unless the condition is: "Whose name is exactly equal to this string", is to loop through the entire map and return all matching entries. Actual DBs are smarter, in that you can add an index so that such queries can be fast even if you have millions of dinos, but that involves programming concepts that are considerably more complicated than what's going on in this code. I'd assume the intent of this exercise is just to write it simply, and loop through every dino, returning only the ones that match the condition. This means you need to make an ArrayList object (or another collection of your choice), loop through, add only the matches ones, then return that collection.

答案2

得分: 0

目前 printMatchingDinos 暂时没有进行任何过滤。在打印时,您无需删除任何内容。您可以迭代 listOfDinosentrySet,并在打印循环中设置一个条件以进行过滤。

public void printMatchingDinos(int limit) {
  for (Map.Entry<String, Integer> entry : listOfDinos.entrySet()) {
    if (entry.getValue() <= limit)
      System.out.println(entry.getKey() + " - 重量:" + entry.getValue() + "千克");
  }
}

虽然您的要求似乎与预期的输出不符。这些行在调用 addDino 时会被打印出来。

建议:最好为 Dino 创建一个类,其中包含 nameweight 字段,而 DinoDatabase 可能包含 Key-Dino 对的 HashMap 作为字段,其中 Key 唯一地标识每个恐龙。

英文:

Currently printMatchingDinos not filtering anything now. You don't need to remove anything to print out. You can iterate entrySet of listOfDinos and just put a condition to filter out in the loop when printing.

public void printMatchingDinos(int limit) {
for (Map.Entry&lt;String, Integer&gt; entry : listOfDinos.entrySet()) {
if (entry.getValue() &lt;= limit)
System.out.println(entry.getKey() + &quot;- Weight: &quot; + entry.getValue() + &quot;kg&quot;);
}
}

Though your requirement doesn't match the expected output. Those lines are printed when addDino called.

Suggestion: It's better to create a class for Dino with field name & weight and DinoDatabase may contain HashMap of Key-Dino pair as a field where Key is uniquely identify every Dino.

huangapple
  • 本文由 发表于 2020年10月25日 17:20:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64522121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定