简体   繁体   中英

Removing the last object in an array in Java?

A quick overview of my program: I am making the game War. So when the play button is clicked, two new cards show up with random values. Which ever card has the higher value wins, and a rectangle appears in the middle of the window. As the game goes on, who ever wins has more rectangles pushed to their side (either to the left or right depending on which card wins), but the trick is that if for example the card on the left wins the first three, then the card on the right wins 1, a rectangle is removed, meaning only 2 are going to the left. If the right wins again, another is removed, etc. The rectangle is created in a separate class called Bar, and here is what I have to create an array with a rectangle that goes to the left.

 Bar newBar = new Bar(300,250); counter = d++; newBar = new Bar(300-(counter*30), 250); if(numDi >= bars.length){ //You want it to always be higher Bar[] temp = new Bar[bars.length +1]; for(int i = 0; i < bars.length; i++){ temp[i] = bars[i]; } bars = temp; //increments bars by 1 } bars[numDi++] = newBar; 

The idea I have is that I could create an if statement which checks who won and also who won the last game. And if the opposing player won the last game, I would need to subtract a rectangle. But how would I go about subtracting the rectangle? And as a side note, I can not use any sort of lists.

You can use a single integer counter. When the right side wins increment it by 1 and when the left side wins decrement it by 1. This way you can easily test with an if statement who has been winning lately and control what happens depending on who wins.

If you can't use a list or queue then I would suggest using two separate arrays, one for the left side and one for the right side. You can increment and decrement them according to the overall score counter.

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