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

标签 java arrays error-handling hashmap logic

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

错误应该检查数组的长度是否小于 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/

相关文章:

c# - 将 ByteArray 转换为 String 以在 TextBox c# 中使用

javascript - 将数组内的数组转换为平均值

spring - Spring MVC <错误页面>不起作用

java - ViewPager 在返回时跳过 View ,留空

java - 使用 Python 或 Java,创建图表的最佳方式是什么?

java - 如何用java代码关闭程序?

c++ - 根据另一个数组的顺序对一个数组进行排序

c# - 记录错误代码的最佳方法

error-handling - 没有在给定选项或默认选项中指定有效的 “from”地址

java - 我如何优化这个java代码?