【发布时间】:2020-07-12 17:16:59
【问题描述】:
我正在尝试为学校做一个挑战题(我是一个完整的初学者,所以请放轻松)。我需要重新创建游戏 Duck-Duck-Goose。我向用户询问玩家的数量,创建该特定数字的布尔数组,然后将它们全部设置为“真”。我正在尝试遍历一个布尔数组并逐渐将每三个元素变为“假”。一旦它到达数组的末尾,我希望它再次通过数组,重复相同的过程。我也很难将索引设置为下一个元素(因此,如果将第 3 个元素重置为“false”,则数组从第 4 个元素开始计数),然后再次循环遍历数组。目标是在数组中重复这个过程(将每个第 3 个元素变为“假”,直到只剩下一个元素为“真”),然后打印它。
* 我仅限于使用布尔数组 *
这是我的代码:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Welcome to the game of Duck Duck Goose!!!");
System.out.println("Please enter the number of players:");
int players=scan.nextInt();
boolean [] game=new boolean[players];
for(int a=0;a<players;a++){ //set all players to 'true'
game[a]=true;
}
if(players>=1){
int turns=players-1;
while(turns>=1){
for(int i=0;i<players;i=i+3){
if(game[i]=true){
game[i]=false;
turns--;
}
}
}
}
else{ // if there is less than 1 player, end the program
System.out.println("Try to get more players!");
System.exit(0);
}
System.out.println("YaaaaY");
for(int j=0;j<players;j++){
if(game[j]==true){ // look through the array and declare the winner
System.out.println("The "+j+" player won!");
}
}
}
}
当我运行它时,我得到以下输出:
*欢迎来到鸭鸭鹅游戏!!!
请输入玩家人数:
10(仅作为示例)
呀呀呀
1 名玩家获胜!
2 人获胜!
4 人获胜!
5 人获胜!
7 人获胜!
8 人获胜!*
我做错了什么???如何使循环多次遍历数组并删除每个第三个元素?如何使循环不是每次都从开头开始,而是从“淘汰”玩家之后的索引开始?我不应该在 at 处使用循环吗?
我对此一无所知。非常感谢任何帮助:)
【问题讨论】:
标签: java arrays loops boolean iteration