gpt4 book ai didi

java - 检查数组的长度并检查 HashMap 键是否在 HashMap 中(Java、Arrays、HashMap)

转载 作者:行者123 更新时间:2023-12-01 10:34:57 27 4
gpt4 key购买 nike

我正在尝试进行一些错误捕获。

错误应该检查数组的长度是否小于 2,并检查 HashMap 是否包含用户输入的键。

捕获的错误必须仅使用 if 语句,并且必须使用 .length() 方法,并且必须使用 HashMap java API 中的 .get() 方法。

我已经像这样声明了 HashMap:

 private HashMap <String, Shape> shapes;

下面是我的其余代码。

        String basicCommand = commands[0];
String moreCommands = commands[1];

int size = commands.length;

if(size < 2 && shapes.get(commands[1]).equals(commands[0])){

if(basicCommand.equals("circle")) {
makeACircle(commands);
}
else if(basicCommand.equals("help")) {
printHelp();
}
else if(moreCommands.equals("left")){
moveLeft(commands);
}
else if(moreCommands.equals("down")){
shapes.get(commands[0]).moveDown();
}
else if(moreCommands.equals("up")){
shapes.get(commands[0]).moveUp();
}
else if(moreCommands.equals("right")){
shapes.get(commands[0]).moveRight();
}
else if(moreCommands.equals("visible")){
shapes.get(commands[0]).makeVisible();
}
else if(moreCommands.equals("invisible")){
shapes.get(commands[0]).makeInvisible();
}
else if(commands[0].equals("forget")){
shapes.remove(commands[1]).makeInvisible();
}
else {
System.out.println("Unknown command: " + basicCommand);
}
}
else{
System.out.println("error");
}
}

最佳答案

通过方法检查map是否包含key

shapes.containsKey(yourKey);

以及 map 中元素的大小(如果这是您通过该方法寻找的内容):

shapes.entrySet().size();

希望对您有所帮助。

关于java - 检查数组的长度并检查 HashMap 键是否在 HashMap 中(Java、Arrays、HashMap),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34818614/

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