I'm trying to make a game in Java, and I've got already something. But i want to make the Player shoot bullets.
I've came up with the idea to make an object array, and put all the Bullet instances into the array. then in a thread, I want to make them all move(all the objects in the array).
This is what I put in the main class:
Bullet[] BulletArray;
public int Bullets = 0;
public void run() {
for(int i = 0; i < Bullets; i++){
BulletArray[i].Step();
}
if(Key.FireKey){
BulletArray[Bullets + 1] = new Bullet();
Bullets += 1;
}
}
I've just included the basic stuff, i.e. The run function runs fine, in the original code.
The code doesn't work, it gives me an error when I press Fire. The error is somewhere at
BulletArray[Bullets + 1] = new Bullet();
I hope you understand what I mean.
Well, for starters, your BulletArray is never initialized.
When you enter run(), your for() loop appears to work fine because it does not actually enter the block. Your int i = 0 is declared and is already greater than or equal to your limit, which is the int Bullet = 0. This means that the body of the loop never executes.
Then, when you press the Key.FireKey, it attempts to reference an array index that doesn't exist. It can't exist, because the array has never been initialized.
To initialize your array, you will need to do something more like this:
private int maxBullets = 10;
Bullet[] bulletArray = new Bullet[maxBullets];
Then your for() loop will actually enter. Note that in your Key.FireKey block, however, that you will have to perform some checking to make sure that you don't get an IndexOutOfBoundsException by trying to fire more bullets than you've created. i.e.,
if(Key.FireKey) {
if(bullets < maxBullets) {
bulletArray[++bullets] = new Bullet();
}
}
Related
I am passing some parameters in the URL and then I add them in a list. My list has a limit of 5 elements. So if someone adds 6th element in the URL the list would simply ignore it. So I am trying to use a counter but the logic is not working as desired. I am using While loop to achieve this. So if list size is smaller than 5 set the agencyCds otherwise just return the list.
private List<IUiIntegrationDto> generateViewIntegrationReportData(ESignatureIntegrationConfig eSignConfig) throws Exception {
int counter = 1;
if(eSignConfig.getAdditionalAgencyCds() != null ) {
List<String> combinedAgencyCds = new ArrayList<String>();
for(String agencyCd : eSignConfig.getAgencyCd()) {
combinedAgencyCds.add(agencyCd);
}
StringTokenizer token = new StringTokenizer(eSignConfig.getAdditionalAgencyCds().toString(), StringConstants.COMMA);
while(token.hasMoreTokens()) {
combinedAgencyCds.add(token.nextToken());
}
while(combinedAgencyCds.size() < 5) {
counter = counter + 1;
eSignConfig.setAgencyCd(combinedAgencyCds);
}
// eSignConfig.setAgencyCd(combinedAgencyCds);
}
List<IUiIntegrationDto> intgList = getUiIntegrationManager().retrieveUiIntegrationReportData(eSignConfig.getAgencyCd(), eSignConfig.getCreatedDays(),
eSignConfig.getLob(), eSignConfig.getTransactionStatus(), eSignConfig.getAccounts(), eSignConfig.getSortKey(), eSignConfig.getSortOrder());
return intgList;
}
I am not completely sure about this logic if it is correct or if there is nay better approach.
Thanks
Try this instead of the last while in your code:
if(combinedAgencyCds.size() <= 5) {
eSignConfig.setAgencyCd(combinedAgencyCds);
} else {
eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, 5));
}
The full combined list will then be used if it is less than 5 in size. Otherwise, only the first 5 elements are used.
Edit: Or even better:
eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, Math.min(5, combinedAgencyCds.size())));
Ok so let's break down what your code is currently doing.
int counter = 1;
while(combinedAgencyCds.size() < 5) {
counter = counter + 1;
eSignConfig.setAgencyCd(combinedAgencyCds);
}
This snippet of code has a couple things wrong best I can tell. First, this loop has the possibility of running forever or not at all. Because combinedAgencyCds is never being manipulated, the size won't ever change and the logic being checked in the while loop never does anything. Second, there's a more efficient loop for doing this, assuming you don't need the counter variable outside of its usage in the while loop and that is using for loops.
Example syntax is as follows:
for (int i = 0; i < combinedAgencyCds.size(); i++) {
if (i < 5) {
// Do your logic here.
}
else {
break; // Or handle extra values however you want.
}
}
Notice there is no need for the explicit declaration for a counter variable as "i" counts for you.
Now in your actual logic in the loop, I'm not sure what the setAgencyCd method does, but if it simply sets a list variable in the eSignConfig like it appears to, repeating it over and over isn't going to do anything. From what I can see in your code, you are setting a variable with the same value 5 times. If you need any more explanation just let me know and I will be happy to revise the answer.
edit: As I was writing this post, I made my code simpler (lost arrays entirely) and got it working. Yet I am still not sure why this specific code won't work, so I'll keep the question.
Hello.
I am writing a small puzzle game in Java (using Eclipse 4.4.2) and stumbled upon a problem inside one of my methods. Basically - it won't complete the method, it just exits the method after the for loop is done without any warnings or errors (I'm not catching exceptions either). I hope I missed something simple..
Details:
I have a method to set the colors of an object and up to 5 other objects that are linked to it through lines. I set up the color of the main object, then find the linked objects through for-loops and in the end change their colors as well. (Double checked the code for Lines, there are simple return methods and nestA and nestB as data - no problem there). lines is an array with a length of 50, nests as its members.
Here's the code:
public void highlightNests(Nest nest) {
//setting the color of the main object (a nest).
Mappers.setColor(nest, nestHighlight);
//resetting the array. Temp solution, had a return method earlier,
//this is part of the debugging.
connectedNests = null;
connectedNests = new Nest[5];
int i = 0;
Gdx.app.log("highlightNests()", "starting the loop");
for (int j=0; j<lines.length; j++) {
if (lines[j].getNestA() == nest) {
connectedNests[i] = lines[j].getNestB();
i++;
}
if (lines[j].getNestB() == nest) {
connectedNests[i] = lines[j].getNestA();
i++;
}
}
//This is where the program exits the method. The following
//lines are not run.
Gdx.app.log("highlightNests()", "entering loop");
for (int l=0; i<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
}
Deleting the middle section makes the end part run, so there are no errors in the last part.
Your second loop is completely wrong, you declare the counter as l and increment another counter i, you should use l<connectedNests.length change it like this:
for (int l=0; l<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
And the program won't finish method and exits before the loop because, it doesn't even enter the loop as it's incorrect.
You have to use l instead of i in condition like,
for (int l=0; l<connectedNests.length; l++)...
//---------^ l not i
I created two methods for my Bingo Game in Java. One method creates a new board which populates the Bingo Board with integers according to the Bingo rule (1-75). My second method generates random numbers with a range of 1 - 75.
public static int drawNum(){
Random rand = new Random();
int num = rand.nextInt(75)+1;
return num;
}
public static void bingoCard(){
int [][]card=new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
int tmp = 0;
for(int i = 0; i <= 4; i++){
for(int row = 0; row < card.length; row++){
while(!valid){
tmp = (int)(Math.random() * 15) + 1 + 15 * i;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
valid = false;
}
}
card[2][2] = 0;
//create array to make title.
String title []={"B","I","N","G","O"};
for(int i=0;i<title.length;i++){
System.out.print(title[i]+ "\t");
}
System.out.println();
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
System.out.print(card[row][col]+ "\t");
}
System.out.println();
}
}
What I need help with is, how do I check whether or not the drawNum() method corresponds to any values stored inside my bingoCard() array? If so, print out a new array with the integers filled in. If the condition is met for a bingo, then you win.
I hope I don't make it sound like I want you to do it for me, but I am confused as to how to start coding that part. Thank you.
This my recommendation - Learn Object Oriented Programming immediately
I see you are using objects provided in the JDK, so why not learn to make your own?
Make two classes with the following methods (-) and members (+) (PS. This is not a formal way to document code)
BingoCard
+list of numbers on card
-reset() : gets new numbers for this card
-test(BingoDrawer) : Tests to see if this card won on this drawing
-toString() : returns a String representation of this card
BingoDrawer
+list of numbers drawn
-reset() : draws new numbers
-hasNumber(int number) : tests if this number was drawn
-toString() : returns a String representation of this drawing
One more suggestions
Instead of keeping track of what you used, keep track of what you have not used, it will make things much easier because you can just choose stuff from that list randomly. Unlike your current action which is choosing (a logical number) from thin air and hoping (which causes issues) it is not a collision
If you follow my recommendation you can write code like this
public static void main(String[] args) {
BingoCard bc = new BingoCard();
BingoDrawer bd = new BingoDrawer();
while(thePlayerWantsToPlay()) { //function to be defined by you
bc.reset();
bd.reset();
System.out.println(bc);
System.out.println(bd);
System.out.println(bc.test(bd));
}
}
You can take it a step further and make a BingoGame class and do what I did in main there and just create an instance of BingoGame and call some start method on the object.
For checking if you have the number in your board, read through the board in a similar manner as you do for the already_used numbers, except with the number the user just entered.
The conditions for the user to win should be checked after the board has another number guessed.
There are a few ways to do this, a simple one would be to iterate over every possible pattern that could win, checking to see if there are tokens there.
All of this would be in a loop, that goes a little like this:
Set up board via user entering numbers.
Start loop
set either a timer to wait for, or wait for a keypress (so the game doesn't just play really fast)
Get random number
Possibly add to board
Check if winner
if winner, break the loop and do something else.
Print the new board out.
(end of loop)
If they got here, that could mean they won!
Wait to exit
You can just write it out as pseudo-code and fill in the methods after that. It usually helps to work on these things in a top-down fashion. So, for bingo you might have:
board = generateBoard();
while (!bingoFound(board)) {
number = drawNumber();
board = stampNumbers(board, number);
}
If that makes sense, you can go a step deeper and define each method. For example, bingoFound might look like:
public boolean bingoFound(int[][] board) {
boolean wasFound = bingoRowFound(board)
|| bingoColFound(board)
|| bingoDiagonalFound(board);
return wasFound;
}
Again, I've defined everything in (mostly) pseudo-code. If this looks ok, you can move a step deeper. Let's define the bingoRowFound method.
public boolean bingoRowFound(int[][] board) {
for (int row = 0; row < NUM_ROWS; row++) {
boolean rowIsABingo = true;
for (int col = 0; col < NUM_COLS; col++) {
// We have to check that everything up until this point has
// been marked off. I am using -1 to indicate that a spot has
// been marked.
rowIsABingo = rowIsABingo && board[row][col] == -1;
}
if (rowIsABingo) { return rowIsABingo; }
}
return false; // If we didn't find a bingo, return false.
}
Some of the methods (like drawNumber) will be really easy to implement. Others, like looking for a diagonal bingo might be a bit more difficult.
Feb 12 2014 Update:
Retracted code, since this was a college course assignment, and I want to prevent people just copying the code. I almost got in trouble for being accused of sharing code (which is a nono in assignments) when another student lifted my code from my Github repo and sent it in as their own.
There were two classes, one main class and a class to hold my methods and constructors.
BINGOFINAL.java was my main class.
Bingo_Card.java held my constructor and methods.
If you want to run this, make sure you create a new project called BINGOFINAL, and put Bingo_Card.java into that same */src/ extension.
here's the deal, I have to make a game that resembles PacMan, with a map, points, ghosts, etc.
The whole thing works as an array[8][8], it reads the positions of walls and the initial position of ghosts from a .txt file, PacMan starts at a fixed location and Fruits are random. Any blank space at the beginning of the game gets filled with a simple point pellet.
I've got the map done, it shows it and everything, but I can't seem to come up with a method that allows the player to control PacMan with the keyboard... This is what I've tried so far...
In the Player class
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String mov = read.readLine();
if (mov.equals("w"))
{
PacMan.MoveU();
}
It then repeats that for the other movement keys.
The individual Move methods in PacMan class look like this
public static void MoverR()
{
for (int i=0;i<Tablero.length;i++)
{
for (int j=0;j<Tablero.length;j++)
{
if (Tablero[i][j] instanceof PacMan)
Tablero[i][j]=null;
Tablero[i][j+1]=new PacMan();
}
}
}
}
This obviously isn't working, so I'm wondering if anyone can help me with a more efficient way to do this? I really don't mind starting these two classes from scratch...
Thanks.
It always gives me an ArrayOutOfBounds Exception
The ArrayOutOfBounds Exception is caused by Tablero[i][j+1]=new PacMan(); when j == 7, because you try to access to an invalid position (Tablero[i][8]).
anyone can help me with a more efficient way to do this?
You don't need to check the whole array to find out the position of Pacman, you could store the position as a private variable of Pacman, but in that case you shouldn't create a new instance of Pacman every time you need to move it, like you are doing with your current implementation.
One reason why you get ArrayOutOfBoundsException is the fact that in your loop you're moving PacMan to position [i][j +1], where j + 1 may be greater than array length.
You need to check if j + 1 < Tablero.length when you're 'moving' PacMan.
Also you can simply move the same instance of PacMan instead of creating a new one:
...
if (Tablero[i][j] instanceof PacMan) {
if (j + 1 < Tablero.length) {
Tablero[i][j+1] = Tablero[i][j];
Tablero[i][j] = null;
}
}
Im trying to write a game of Yahtzee as part of an online course (not actually enrolled, just playing along at home) I have hit a bit of a wall manipulating values in the array that keeps track of the dice values. This is the section of code that seems to be causing trouble;
for (int i=0; i<N_DICE; i++){ //goes through each die.
if (display.isDieSelected(i) == false){ //checks if player wants to reroll the die.
dice [i] = dice[i];//problem line-should reassign the same value back to the die.
}
else {
dice [i] = rgen.nextInt(1, 6);
}
}
Assigning a new random number works, and if I roll all 5 dice every turn its happy.
I've changed the offending line to dice[i]=1 for testing purposes and while it takes some fun out of the game, the program works, so I'm thinking its something simple I'm doing wrong with that line.
I've tried assigning dice[i] to a temp variable (inside and out of the if loop) and then assigning temp back to dice[i].
I've tried just leaving the if loop empty.
I've tried setting it up as a multi dimesional array with a seperate array for each roll.
I've tried adding a cast (didnt think that'd do it but I was out of ideas).
All of these have had the same results.
Only been programming a few weeks, I'd be very gratefull if someone could tell me what I'm doing wrong.
Not sure what you're trying to do with that line:
dice[i] = dice[i];
Since it's a NOP, why not just omit it?
I don't really see the purpose of:
dice[i] = dice[i]
Can't you just use something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i)){
dice [i] = rgen.nextInt(1, 6);
}
}
The code looks completely correct, although I would write it a bit more compactly:
for (int i = 0; i < N_DICE; i++) {
if (display.isDieSelected(i)) {
dice[i] = rgen.nextInt(1, 6);
}
}
So your problem probably lies somewhere else. Is dice a new array, or is it always the same in the program? If it is a field in some class, it should have the final modifier, like this:
public class YahtzeeState {
private final int[] dice = new int[N_DICE];
}
This declaration makes sure that the dice array cannot be replaced later with a completely different array. The values in the array can still be changed though.
How is the dice-array initialized? I don't know your entire code but I could imagine that it doesn't work because the dice-array gets it values only in this loop?
Maybe you should try something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i) || dice[i] == null)
dice [i] = rgen.nextInt(1, 6);
}