【问题标题】:Some issue with an enhanced for loop-SimpleDotCom增强的 for loop-SimpleDotCom 的一些问题
【发布时间】:2014-10-29 09:26:54
【问题描述】:

这是本书的修改示例,Head First Java。这是一种战舰游戏,其中一个 3 元素阵列被用作战舰。用户必须猜测这 3 个位置。目前,我已将船舶位置的值硬编码为 2、3、4。当用户猜到正确的位置时,“Hit”被打印出来。如果不是,则打印“Miss”。如果用户猜到所有 3 个位置,则打印“Kill”。但我有一个问题。目前,如果用户多次进入同一个位置,它仍然会命中。我试图通过将已经被命中的变量(int cell)的值更改为“-1”来解决这个问题。但由于某种原因,这也没有解决它。请告诉我我做错了什么。

public class Game {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int [] location = {2,3,4};
        SimpleDotCom firstGame = new SimpleDotCom();

        firstGame.setLocation(location);

        firstGame.checkYourself("2");
        firstGame.checkYourself("2");
        //firstGame.checkYourself("2");
    }

}


public class SimpleDotCom {
    int [] loc = null;
    int numOfHits = 0;

    void setLocation (int [] cellLocation){
        loc = cellLocation;
    }

    void checkYourself(String userGuess){

        int guess = Integer.parseInt(userGuess);
        String result = "Miss";

        for(int cell:loc){
                        if (guess == cell){
                            result = "Hit";
                            numOfHits++;
                            cell = -1;
                            break;
                            }
                        if (numOfHits==loc.length){
                            result = "Kill";
                            }

        }
        System.out.print("Result: " + result);
        System.out.println(" ** Num of Hits: " + numOfHits);
}

    }

【问题讨论】:

  • 程序很短很简单,你调试过吗?
  • 没有。我已经忘记如何调试了。现在用谷歌搜索。
  • 如果打印了“Hit”,您必须从数组中删除该元素。
  • 我没有删除那个元素,我只是将它的值更改为用户不会猜到的值(在本例中为 -1)。是一样的吧?
  • 你们真的很快。谢谢大家。

标签: java


【解决方案1】:

当您循环访问 loc 时,您会为每个位置获得一个 int cell。问题是该变量与数组没有任何连接,它只是一个副本。如果您更改它,原始数组将不会发生任何事情。我建议使用传统的for(;;) 循环loc,并使用循环逻辑中的当前数组索引将正确的“单元格”设置为-1。

【讨论】:

  • 谢谢,我不知道。
【解决方案2】:

因为您将 -1 分配给局部变量。实际上没有在数组中更新

 for(int cell:loc){  // cell is local copy of element in array is you have array of primitive int
    if (guess == cell){
       result = "Hit";
       numOfHits++;
       cell = -1;
       break;
     }
     if (numOfHits==loc.length){
         result = "Kill";
      }
  }

您可以为此使用传统的 for 循环,也可以使用 List,它具有添加删除元素的方法。

【讨论】:

    【解决方案3】:

    您需要在正确的索引处更新数组,而不是简单地更改 cell 变量的值,该变量仅引用当前迭代状态下的数组元素。

    您可能应该为此使用传统的 for 循环,因为您无法从增强的 for 循环中免费获取索引。

    for (int i = 0; i < loc.length; i++) {
       //code...
    
       loc[i] = -1; //instead of cell = -1; 
    }
    

    【讨论】:

    • 谢谢。这解决了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多