[英]Check length of an array and check if HashMap key is in the HashMap (Java, Arrays, HashMaps)
我正在嘗試進行一些錯誤捕獲。
該錯誤應檢查數組的長度是否小於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");
}
}
通過方法檢查地圖是否包含鍵
shapes.containsKey(yourKey);
以及地圖中元素的大小(如果這是您通過該方法尋找的內容):
shapes.entrySet().size();
希望對您有所幫助。
感謝Luciano Almeida。 你是對的!!
這就是我根據您的回答解決問題的方式。
如果你們對我的下面的代碼有任何改進或建議,請發表評論。 謝謝!
私人無效execute(String []命令){
String basicCommand = commands[0];
String moreCommands = commands[1];
int size = commands.length;
if(basicCommand.equals("circle")) {
makeACircle(commands);
}
else if(basicCommand.equals("help")) {
printHelp();
}
else if(shapes.containsKey(commands[0])){
if(moreCommands.equals("left")){
shapes.get(commands[0]).moveLeft();
}
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{
System.out.println("error");
}
}
else if(commands[0].equals("forget")){
shapes.get(commands[1]).makeInvisible();
shapes.remove(commands[1]);
}
else {
System.out.println("Unknown command: " + basicCommand);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.