简体   繁体   中英

Removing an element from an array in a loop in Java

After transferring from C to Java I have learned that Java contains many functions that can do the job for you, so to speak, unlike in C where you must do things manually.

I am currently designing an OOP board game, in which multiple players are allowed to pick a playing piece, that represents them throughout the game. I have stored the playing pieces in an array, and then asked the number of players to pick a playing piece. However, they are not allowed to pick the same playing piece as the player before them, for obvious reasons. Therefore, my question is there a function that allows me to remove one of the picked playing pieces from the array or must I do this manually, so to speak. My code is below, if needed:

String[] potential_player_pieces = new String[10]; // Array storing the playing pieces available
potential_player_pieces[0]= "*";
potential_player_pieces[1]= "|";
potential_player_pieces[2]= "?";
potential_player_pieces[3]= "@";
potential_player_pieces[4]= "&";
potential_player_pieces[5]= "¬";
potential_player_pieces[6]= "!";
potential_player_pieces[7]= "%";
potential_player_pieces[8]= "<\n";

String[] player_pieces = new String[players+1]; // String to store the playing pieces that the players have chosen

for (int i=1; i<=players; i++) // Loops to the number of players and asks them what playing piece they want
{
    System.out.print("Player " + i + " pick a playing piece:"); // Asks the players the question
    for (int j=0; j<=8; j++){
        System.out.print(potential_player_pieces[j]); // Displays the possible playing pieces  
    }
    player_pieces[i] = reader.nextLine();//Saves the player chioces to the array made above
}

I would introduce a new List<String> of available options for a current player:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

...

List<String> availableOptions = new ArrayList<>(
    Arrays.asList(potential_player_pieces)
);

and remove the chosen element after the pick is done:

for (int i = 0; i < players; ++i) {
    System.out.println("Player " + i + " pick a playing piece: " + availableOptions);
    availableOptions.remove(player_pieces[i] = reader.nextLine());
}

You also might have shortened initialisation of the array to:

String[] potentialPlayerPieces = new String[] {"*", "|", ..., "<"};

Note that I have renamed the variable to look more Javaish .

I would like to suggest a HashMap in your case. I think this data structure is effective and serves your purpose.

Map<String, Integer> pieceMap = new HashMap<String, Integer>();
// HashMaps stores the value as a key value format. 
// Here the keys are the piece options 
// And the 0 is indicating that, primarily the piece is not used. 
pieceMap.put("*", 0);
pieceMap.put("|", 0);
pieceMap.put("?", 0);
pieceMap.put("@", 0);
pieceMap.put("&", 0);
pieceMap.put("¬", 0);
pieceMap.put("!", 0);
pieceMap.put("%", 0);
pieceMap.put("<\n", 0);

String[] player_pieces = new String[players + 1]; 
for (int i = 0; i < players; i++) {
    System.out.print("Player " + i + " pick a playing piece:"); // Asks the players the question

    printAvailablePieces(pieceMap);

    String piecePlayed = reader.nextLine();

    if(pieceMap.containsKey(piecePlayed) && pieceMap.get(piecePlayed).equals(0)) {
        // The piece has not used yet. 
        pieceMap.put(piecePlayed, 1);
        player_pieces[i] = piecePlayed;
    } else {
        // The piece was played before
        System.out.println("Please play a different piece");
        i--; // Take the user input again. 
    }
}

public void printAvailablePieces(HashMap<String, Integer> pieceMap) {
    for (Map.Entry<String, Integer> entry : pieceMap.entrySet()) 
        if(entry.getValue().equals(0)) System.out.print(entry.getKey() + " ");
}

Hope that helps.

I would suggest using a HashSet instead of an array to store all the board pieces. Once a player chooses a piece it could be easily removed from the set by calling remove . Also you could validate the choice by calling the contains method on the set.

Use List and HashMap

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Temp {

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

        List<String> potential_player_pieces = new ArrayList<String>();//Array storing the playing pieces available
             potential_player_pieces.add("*");
             potential_player_pieces.add("|");
             potential_player_pieces.add( "?");
             potential_player_pieces.add( "@");
             potential_player_pieces.add( "&");
             potential_player_pieces.add( "¬");
             potential_player_pieces.add( "!");
             potential_player_pieces.add( "%");
             potential_player_pieces.add( "<\n");
             Collections.sort(potential_player_pieces);

             System.out.println(potential_player_pieces);

             int length=potential_player_pieces.size();
             Scanner reader= new Scanner(System.in);

           Map<Integer,String> player_pieces = new HashMap<Integer,String>();//String to store the playing pieces that the players have chosen
                 for (int i=1; i<=length; i++)//Loops to the number of players and  asks them what playing piece they want
                 {
                     System.out.print("Player " + i + " pick a playing piece: ");//Asks the players the question


                     for (int j=0; j<potential_player_pieces.size(); j++){

                            if(j==0) 
                            {
                                System.out.print(potential_player_pieces.get(0)+"\n");
                                player_pieces.put(i, potential_player_pieces.get(0));
                                potential_player_pieces.remove(0);

                            }
                            if(potential_player_pieces.size()>0)
                         System.out.println(potential_player_pieces.get(j)); //Displays the possible playing pieces


                     }

                      //Saves the player chioces to the array made above

                 }

                 System.out.println(player_pieces);

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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