簡體   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