gpt4 book ai didi

java - 我怎样才能正确打印这个?

转载 作者:行者123 更新时间:2023-12-01 15:37:11 25 4
gpt4 key购买 nike

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

    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");
}

我必须承认我不明白你想要做什么,但至少这段代码达到了你的代码的预期目的。

关于java - 我怎样才能正确打印这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8700346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com