繁体   English   中英

我该如何正确打印?

[英]How can i print this right?

这个简单的程序会询问玩家的数量,他们的名字和(最后一个)计数他们的得分。但是我不知道为什么它不转到下一个玩家。看看我的代码:

    Scanner scanner = new Scanner(System.in);
    HashMap<String,Integer> players= new HashMap<String,Integer>();

    System.out.printf("Give the number of the players: ");
    int numOfPlayers = scanner.nextInt();

    for(int k=1;k<=numOfPlayers;k++)
    {
        System.out.printf("Give the name of player %d: ",k);
        String nameOfPlayer= scanner.next();
        players.put(nameOfPlayer,0);//score=0
    }

    //This for finally returns the score 
    for(String name:players.keySet())
    { 
      int k=1;
      do{ 
          System.out.println("Name of player in this round: "+name);
           System.out.printf("Give me your word: ");
           String nameOfWord= scanner.next();

          //::::::::::::::::::::::
          //::::::::::::::::::::::

          int score=players.get(name)+10;
          //This will update the corresponding entry in HashMap
          players.put(name,score);
          System.out.println("The Player "+name+" has "+players.get(name)+" points ");
    }while(k>0);
}
}  }

返回:

 Give the number of the players: 2
 Give the name of player 1: A
 Give the name of player 2: B
 Name of player in this round: A
 Give me your word: ABC
 The Player A has 10 points 
 Name of player in this round: A
 Give me your word:......
........

但是我想要在它计算出A的分数后再计算出B的分数。我该怎么办?我在做什么错?

摆脱需要的do while -您不需要它。 另外,在Map “适当地”迭代。
这是重新设计的代码片段:

// Note this more elegant iteration over a map
for (Map.Entry<String, Integer> entry : players.entrySet()) {
    String name = entry.getKey();
    int score = entry.getValue();
    System.out.println("Name of player in this round: " + name);
    System.out.printf("Give me your word: ");
    String nameOfWord = scanner.next();
    // Some code that uses "nameOfWord"
    score += 10;
    entry.setValue(score); // Note this more elegant use of the API
    System.out.println("The Player " + name + " has " + score + " points");
}

我必须承认,我不理解您要执行的操作,但是至少此代码可以实现您的代码意图。

您无需在do ... while循环中的任何地方更改变量k (这是循环条件中包含的唯一变量)-这意味着它将与第一个玩家永远循环!

如果我正确地解释了您想做什么,则应该完全删除do {} while (k>0)行-您甚至在循环中的任何地方都没有引用k的值,除了条件; 可能是通过其他方式遍历玩家的剩余部分?

或者,如果应该是进行游戏回合的循环(一个回合是每个玩家一回合的集合),那么它的位置错误-应该围绕for ...循环遍历玩家,而不是放在里面; 当然,您还必须为游戏结束提供一个适当的条件-如果它确实取决于您当前使用的k变量,那么此变量也将不得不在某处更改,否则您将返回到永无止境的循环!

但是,如果没有更多信息,很难解释您的代码。 请更新您的问题,以获取更多信息,以了解游戏中的完整回合应该是什么样子,以及游戏结束的条件是什么!

为什么您使用do-while。我看不到它。当然,这是导致问题的原因,因为您从未增加k,对我来说似乎是无限循环

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM