Creating Array of objects and read the information - java

I am creating a Box[] with box objects(i.e.boxes[box1,box2,box3]),then writing a method to access the element in Box[], I encountered no Pointer error.
public class GameState
{
public static final int noOfSquares = 10; // the extent of the board in both directions
public static final int noOfBoxes = 3; // the number of boxes in the game
private Square[][] board; // the current state of the board
private Box[] boxes; // the current state of the boxes
private int score; // the current score
// initialise the instance variables for board
// all squares and all boxes are initially empty
public GameState()
{
score = 0;
board = new Square[10][10];
Box[] boxes = new Box[3];
for(int j =0;j<boxes.length;j++){
boxes[j] = new Box();
}
// return the current state of the board
public Square[][] getBoard()
{
return board;
}
// return the current contents of Box i
public Box getBox(int i)
{
if (0 <= i && i < noOfBoxes) **// here doesn't work**
{
return boxes[i];
}
else {
return null;
}
}
// return the current score
public int getScore()
{
return score;
}
}
}
There are no errors in the box class,in which Box() creates a new null box.
Thanks for help.

You're shadowing the variable boxes. Replace
Box[] boxes = new Box[3];
with
boxes = new Box[3];

Related

Passing an array as a parameter- chess board

I can't see what is wrong, I am trying to pass the gameBoard array (is this not an array?- see constructor) into the findPiece method, but it says it
isn't an array, what should I be passing here to get un updated board? Sorry, I am new to programming but I really appreciate any hints!
public class Game {
private Board gameBoard;
public Game() {
gameBoard = new Board();
}
public void play(Board board) {
EasyIn2 reader = new EasyIn2();
gameBoard = new Board(); //initializes the board so dont need to do so in main
boolean done = false;
while(!done) { //keeps looping when no one has won yet
gameBoard.printBoard();
System.out.println(WHITEPLAYS_MSG);
String pos1 = reader.getString(); //gets user input ... move from... to.... temporary variables
int xFrom=pos1.charAt(0) - 'a'; //to transform the letter
int yFrom=pos1.charAt(1) - '1'; // to transform the number
String pos2 = reader.getString();
int xTo=pos2.charAt(0) - 'a'; //to transform the letter
int yTo=pos2.charAt(1) - '1'; // to transform the number
gameBoard.findPiece(gameBoard,xFrom,yFrom);
}
}
}
public class Board {
private static final int DEFAULT_SIZE = 8; //images for pieces to be displayed on board
private static final char FREE = '.';
private static final char WHITEROOK = '♖';
private static final char BLACKROOK = '♜';
private static final char WHITEBISHOP = '♗';
private static final char BLACKBISHOP = '♝';
private static final char WHITEKING = '♔';
private static final char BLACKKING = '♚';
private static final char WHITEQUEEN = '♕';
private static final char BLACKQUEEN = '♛';
private static final char WHITEKNIGHT = '♘';
private static final char BLACKKNIGHT = '♞';
private static final char WHITEPAWN = '♙';
private static final char BLACKPAWN = '♟';
private int boardsize;
public char[][] board;
public Board() {
this.boardsize = DEFAULT_SIZE;
board = new char[boardsize][boardsize];
// Clear all playable fields
for (int x = 0; x < boardsize; x++)
for (int y = 0; y < boardsize; y++)
board[x][y] = FREE;
board[0][7] = BLACKROOK;
board[2][7] = BLACKBISHOP;
board[5][7] = BLACKBISHOP;
board[7][7] = BLACKROOK;
board[0][0] = WHITEROOK;
board[2][0] = WHITEBISHOP;
board[5][0] = WHITEBISHOP;
board[7][0] = WHITEROOK;
}
public boolean findPiece(char[][] boardIn, int xFrom, int yFrom) { //checks that the player has selected a piece
for (int i = 0; i < boardIn.length; i++) {
for (int j = 0; j < boardIn.length; j++) {
if (boardIn[i][j] == boardIn[xFrom][yFrom]) { //checks the user input co-ordinate is on the board
break;
if (boardIn[xFrom][yFrom] != FREE) {
Piece piece=new Piece(); //checks the piece is real, ie not a free space
piece.getPieceType(xFrom, yFrom);
return true;
} else {
return false;
}
}
}
You should pass gameBoard.board: actually, you are passing the entire instance of that class (gameBoard), not just the array component of it. So, it's right: the error you got said that you are not passing an array.
The findPiece expects a char[][] as the first parameter and not the entire class Board.
You need to call findPiece method with the first parameter as gameBoard.board;

Cannot find ArrayList object

The NumberTile class models a number tile which is an arrayList of 4 integers, the TileGame class inserts a tile into the board, and a test class to start the game. A hand is an arraylist of 5 NumberTiles, but when I compile this, every time I reference to an ArrayList of NumberTile in TileGame, it cannot find the symbol NumberTile.
Do I need to create a package so it would recognize it? My instructor provided most of those statements and I cannot change them. I did not type the other methods because I do not think they are necessary.
Also, the line TileGame game = new TileGame(); says cannot find symbol. What would be the right way to initialize it?
I need any help I can get. Thank you.
Class TileGame:
public class TileGame
{
//provided by instructor
private ArrayList<NumberTile> board ;
// Creates an empty board
public TileGame()
{
//do not modify this method
board = new ArrayList<NumberTile>();
}
// Accessor for the board
public ArrayList<NumberTile> getBoard()
{
// Do not modify this method
return board ;
}
// Creates and returns a hand of 5 random number tiles
public ArrayList<NumberTile> getHand()
{
ArrayList<NumberTile> hand = new ArrayList<NumberTile>() ;
for (int a = 0; a < 5; a++)
{
hand.add(a, new NumberTile());
}
return hand;
}
// If the current tile fits in the board (without rotating) then
// return the index i of a tile in the board so that the current tile
// fits before ti for i = 0..k-1, or return k if the current tile fits
// after the last tile. If the tile does not fit, return -1
public int getIndexForFit(NumberTile currentTile)
{
NumberTile firstTile = board.get(0);
NumberTile lastTile = board.get(board.size() - 1);
if(firstTile.getLeft() == currentTile.getRight())
{
return 0;
}
else if (lastTile.getRight() == currentTile.getLeft())
{
return board.size() - 1;
}
else
{
return -1 ;
}
}
// Call the method getIndexForFit to see whether a tile can be inserted
// into the board. In this method the tile can be rotated. If the tile
// can be inserted, return true. If the tile does not fit after
// rotating (at most 3 times), return false.
public boolean canInsertTile(NumberTile currentTile)
{
//call get index for fit
int canInsert = getIndexForFit(currentTile);
boolean canInsertOrNot = false;;
//if true, modify index
if(canInsert == -1)
{
//rotate
for (int rotations = 0; rotations < 3; rotations++)
{
currentTile.rotate();
int didRotationWork = getIndexForFit(currentTile);
if (didRotationWork == -1)
{
continue;
}
else if (didRotationWork != -1)
{
canInsertOrNot = true;
}
}
return false;
}
else if(canInsert != -1)
{
return true;
}
return canInsertOrNot;
}
// Make a move. I.e. if a tile in the hand fits on the board
// then remove it from the hand and place it in the board. If no tile
// from the hand fits, then add another tile to the hand
public void makeMove(ArrayList<NumberTile> hand)
{
boolean fits;
for (int x = 0; x < hand.size(); x++)
{
//call caninterserttile
fits = canInsertTile(hand.get(x));
if(fits)
{
int index = getIndexForFit(hand.get(x));
board.add(index, hand.get(x));
hand.remove(x);
break;
}
else
{
hand.add(hand.size() -1, new NumberTile());
}
}
}
public String toString()
{
// Do not modify this method
return board.toString() ; // ArrayList as a String
}
} // end of TileGame class
Class NumberTile:
public class NumberTile
{
public ArrayList<Integer> tile = new ArrayList<>();
// Constructs a NumberTile object using 4 random integers in the
// range 1 to 9
public NumberTile()
{
Random generator = new Random() ;
for (int a = 0; a < 4; a++)
{
int random = generator.nextInt(9);
tile.add(a, random);
}
}
// Rotate the tile 90 degrees
public void rotate()
{
int temp = tile.get(0);
tile.set(0, tile.get(1));
tile.set(1, tile.get(3));
tile.set(3, tile.get(2));
tile.set(2, temp);
}
public int getLeft()
{
// Do not modify this method
return tile.get(0) ;
}
public int getRight()
{
// Do not modify this method
return tile.get(2) ;
}
public String toString()
{
String out = "";
out += " "+tile.get(0)+" ";
out += tile.get(1) + " " + tile.get(2);
out += " "+tile.get(3)+" ";
return out;
}
} // end of NumberTile class
Class TileGameTester:
public class TileGameTester {
public static void main(String[] args){
TileGame game = new TileGame();
boolean winner = false;
//get two hands
ArrayList<NumberTile> hand1 = game.getHand();
ArrayList<NumberTile> hand2 = game.getHand();
//create an empty board
System.out.println(game.getBoard());
do{
//make moves
game.makeMove(hand1);
game.makeMove(hand2);
//check if they won
if (hand1.isEmpty() || hand2.isEmpty())
{
winner = true;
}
}while(!winner);
hand1.toString();
hand2.toString();
if (hand1.isEmpty() && hand2.isEmpty())
{
System.out.println("It is a tie!");
}
else if (hand1.isEmpty())
{
System.out.println("Player 1 won!");
}
else if (hand2.isEmpty())
System.out.println("Player 2 won!");
}
}
Though it is incomplete so i am not sure if you are adding data to the arraylist or not but if you are getting Symbol not found .
I am also not able to see any import statements . Did you import the objects
eg TileGameTester should have import -> import com.something.TileGame and import com.something.NumberTile
also check if you have import statement in TileGame and common imports like arraylist
I think you may need to insert "import java.util.Random;" and "import java.util.ArrayList;" between your package declaration (if you have one) and the class declaration in the files where these are used.
You can import TileGame class to TileGameTester class that might solve your issue.

Battleship Project Problems

public class Basic
{
public static int numGuess;
public int guess;
public int numHits = 0;
private static int[] ships;
private boolean hitShip;
public static boolean shipSunk;
private int[]board = new int[5];
public Basic()
{
numGuess = 0;
hitShip = false;
shipSunk = false;
}
public static void setShips (int[] loc)
{
ships = loc;
}
public int Check(int z)
{
for(int cell : ships)
{
if(z == cell)
{
hitShip = true;
System.out.println("\nYou hit an enemy ship!");
numHits++;
numGuess++;
if(numHits == ships.length)
{
shipSunk = true;
System.out.println("\nYou sunk the enemy ship!");
System.out.println("the number of guesses it took you to sink the ship is " + numGuess/3);
break;
}
}
else
{
System.out.println("You've missed the enemy ship!");
}
}
return z;
}
}
So I've been working on this battleship project for school and i made this 1-D board for my game. So far i think I've got my code correct, but now i'm stuck. In my for each loop, since it checks my guess with each of the three values of my ship, it prints whether or not i hit the ship three different times everytime i guess. I'm trying to get my program just to print whether or not i hit the ship once everytime i guess.
import java.util.Scanner;
import java.util.Random;
public class BasicTester
{
public static void main(String[] args)
{
Basic shipp = new Basic(); //initalizes basic class
int ship = (int)(Math.random() * 5); // gives ship a random # between 1 - 5
int ship1;
int ship2;
int guess;
if(ship <= 2)
{
ship1 = ship + 1;
ship2 = ship + 2;
}
else
{
ship1 = ship - 1;
ship2 = ship - 2;
}
int[] locations = {ship, ship1, ship2};// sets array of locations
shipp.setShips(locations); // sets locations to ships in other class
Scanner guesss = new Scanner(System.in); // Scanner
do
{
System.out.println("\nTell me where the enemy ship is.");
guess = guesss.nextInt(); // gives guess the int from Scanner
int resultb = shipp.Check(guess); // puts the int guess through the check method
}
while(Basic.shipSunk == false);
}
}
Instead of having your
else
{
System.out.println("You've missed the enemy ship!");
}
Inside the loop, you should set a flag before the loop
hitIt = false;
Then, when you check against the three "ships", you can set this flag to "true" when you find a hit. Finally, check the flag after the loop. If it is still false, print your message.

Hard time with factory method implementation in java

So, I have a class that represents a game board (4x4), each space is the face value of a die, represented internally by an arraylist. I'm supposed to implement factory methods to generate the board.
public class Board {
static ArrayList<Die> board = new ArrayList<Die>();
public static Board makeFixedBoard(DiceManager dice) {
for (int i = 0; i < 16; i++) {
//add faces
}
return new Board();
}
}
However, I'm having a hard time understanding exactly how to implement the factory method. Here, my return is a new board, but that just creates a new empty board rather than the one I generated.
This is the die class
public class Die {
char[] faces = new char[6];
char facevalue;
public Die(char side1, char side2, char side3, char side4, char side5, char side6){
faces[0] = side1;
faces[1] = side2;
faces[2] = side3;
faces[3] = side4;
faces[4] = side5;
faces[5] = side6;
facevalue = faces[0];
}
public void roll() {
int roll = 0 + (int)(Math.random() * 6);
facevalue = faces[roll];
}
public char getValue() {
return facevalue;
}
There is no need to keep board as static.
private ArrayList<Die> board = new ArrayList<Die>();
public static Board makeFixedBoard(DiceManager dice) {
Board boardInstance = new Board();
for (int i = 0; i < 16; i++) {
//add faces
boardInstance.board.add(die);
}
return boardInstance;
}
You first need to create instance of Board and then in the for loop add the die you create into the boardInstance, after all the die have been added, you return the created instance of the board to the caller.

java text based world moving elements around

I have a project that i cannot for the life of me figure out the moving pattern, whether some object is in the same place as another, or how to interact with each project, here is the first class:
public class AnimalKingdom {
public static final int WORLD_ROWS = 4;
public static final int WORLD_COLUMNS = 4;
public static final int ROUNDS = 10;
public static void main(String[] args) {
Animal[] animals = new Animal[10];
animals[0] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[1] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[2] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[3] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[4] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[5] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[6] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[7] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[8] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
animals[9] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
for (int i = 1; i < ROUNDS; i++) {
showWorld(animals);
doEating(animals);
doMoving(animals);
}
}
public static void showWorld(Animal[] animals) {
System.out.println();
System.out.println("The World");
/* The world is made of rows and columns.
Each location must be big enough to list all the animals
(in case they all show up at that spot at once). So we print
the single character string for each animal, then later add in enough
blanks to ensure that the lines between locations are neatly
drawn. */
for (int r = 0; r < WORLD_ROWS; r++) {
for (int c = 0; c < WORLD_COLUMNS; c++) {
int localAnimals = 0;
for (int a = 0; a < animals.length; a++) {
if (animals[a] != null) { // as animals die, nulls will be left in the array
int ar = animals[a].getRow();
int ac = animals[a].getCol();
if (r == ar && c == ac) { // this animal is local to this location
localAnimals++;
System.out.print(animals[a]); // draw the animal
}
}
}
// create enough blanks to fill out the location
for (int i = 0; i < animals.length-localAnimals; i++) {
System.out.print(" ");
}
System.out.print("|");
}
System.out.println();
}
System.out.println();
}
public static void doEating(Animal[] animals) {
// This needs to be filled in
}
public static void doMoving(Animal[] animals) {
// This needs to be filled in
}
}
And here is the second part of my coding:
import java.util.Random;
public class Animal {
private Random rand = new Random();
private int worldWidth;
private int worldHeight;
private int row;
private int col;
public Animal(int worldHeight, int worldWidth) {
this.worldHeight = worldHeight;
this.worldWidth = worldWidth;
row = rand.nextInt(worldHeight);
col = rand.nextInt(worldWidth);
}
public boolean willEat(Animal anim) {
return false;
}
public void move() {
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public void setRow(int r) {
row = r;
}
public void setCol(int c) {
col = c;
}
public String toString() {
return "";
}
public int getWorldWidth(){
return worldWidth;
}
public int getWorldHeight(){
return worldHeight;
}
public boolean isInSamePlaceAs(Animal other) {
return false; // code needs to be replaced
}
}
Each subclass is named Worm, Bird, and Wolf. Each subclass toString is represented in the form of one char. 'B' for Bird, '.' for Worm, and 'W' for Wolf. The worms can move left and right, remembering the direction they are going in and reverse if they hit a wall or end/beginning of array. The Bird moves diagonally in the world. The Wolf is allowed to move in any direction.
I just need help with starting to make movements in the doMoving(), help identify isInSamePlaceAs() and help doEating(). Birds eat worms, Wolves eat Birds, and worms do nothing.

Categories

Resources