Cannot find ArrayList object - java

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.

Related

(Java) ArrayList length becomes zero after a nonzero method

I am using an ArrayList to store objects that are "valid" for the purposes of my program and referencing it later in the same class file.
private static ArrayList<TownResource> validResources = new ArrayList<>();
A public method is called, which then calls a private method within the class that makes validResources's size nonzero.
public static boolean detection(int row, int col, TownResource[][] rArray, ResourceEnum[][][] bT, BuildingEnum buildingType) {
int checkTime = 0;
int patternIndex = 0;
try {
for (int i = 1; i < checkTime+1; i++) {
if (compare(row, col, rArray, buildingTemplate[patternIndex], buildingType)) {
for (int j = 0; j < validResources.size(); j++) {
validResources.get(j).setScannedBuilding(buildingType);
}
System.out.println("Size at compare" + validResources.size());
return true;
}
}
}
catch (ArrayIndexOutOfBoundsException e){
//System.out.println("Out of bounds exception?");
}
return false;
}
The compare method is a private method that on one condition, may clear validResources.
private static boolean compare(int row, int col, TownResource[][] rArray, ResourceEnum[][] buildingTemplate, BuildingEnum buildingType) {
for (int r = 0; r < buildingTemplate.length; r++) {
for (int c = 0; c < buildingTemplate[r].length; c++) {
if (match(rArray[row+r][col+c], buildingTemplate[r][c])) {
//System.out.println("Successful comparison at " + (row+r) + ", " + (col+c));
}
else {
validResources.clear();
return false;
}
}
}
return true;
}
match is what sets validResources to be nonzero in size:
private static boolean match(TownResource toBeChecked, ResourceEnum checker) {
if (checker == ResourceEnum.NONE) {
return true;
}
else if (toBeChecked.getResource() == checker) {
validResources.add(toBeChecked);
return true;
}
return false;
}
However, when I know validResources to be nonzero in size(this causes detection to return true which triggers a new method placement), it becomes zero.
public static void placement(TownResource[][] rArray, Building[][] bArray, BuildingEnum building) {
// other parts of method commented out for example
System.out.println(validResources.size());
for (int i = 0; i < validResources.size(); i++) {
System.out.println("Is this statement firing?");
System.out.println(validResources.get(i).getResource());
validResources.get(i).setResource(ResourceEnum.NONE);
}
Have I declared validResources incorrectly? Or is there something else at play?
Thank you.
This was an error in how I executed detection(). This method is called by another method within another class when iterating through a 2D array. The ArrayList validResources becomes nonempty in one check, but gets overwritten by another as a result of the program not calling placement until every object in the 2D array had detection called on it. I changed this to call placement immediately.

How check if the array is full and only add to it if it's not? [duplicate]

I've got array. I've got an isFull method, which checks if the array is full, but I don't know how to use this to check if it's full, then if it's not full add to the array, otherwise disregard the add call.
The array should take 10 elements and then not accept any more. After 10 elements, it should 'be full' and disregard any addSpy calls.
How would you implement this?
public class ConcreteSubject extends AbstractSubject {
public int arySize;
private int i = 0;
private static AbstractSpy[] spies;
public ConcreteSubject(int a) {
arySize = a;
spies = new AbstractSpy[a];
}
#Override
public void addSpy(AbstractSpy spy) {
if (spies.length < 10) {
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
public void isFull() {
//1
boolean b = false;
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
b = true;
}
}
if (!b) {
System.out.println("Array is full");
} else {
System.out.println("Array not full");
}
}
public class TestSpies {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject(10);
AbstractSpy spy = new ConcreteSpy();
AbstractSpy[] spies = new AbstractSpy[10];
cs.addSpy(spy);
cs.addSpy(spy);
cs.addSpy(spy);
cs.isFull();
}
}
spies.length < 10 isn't correct. It should be spies.length > 0 && i < spies.length to make sure that the following assignment spies[i] = spy; is always valid.
void isFull() should be boolean isFull(). Your implementation looks OK, just return b. full is a tricky word because technically an array is always "full". A better adjective would be populated, filled.
Since addSpy isn't filling null gaps but simply adds a spy to the end, isFull could be rewritten to return spies.length == i;.
The simplest way of doing it would be like that:
#Override
public void addSpy(AbstractSpy spy) {
if (!isFull())
{
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
To use that, you should change your isFull method to:
public boolean isFull() {
for (int i = 0; i < spies.length; i++) {
if (spies[i] == null) {
return false;
}
}
return true;
}
Keep a track of the number of filled cells of the array using a variable. And before inserting anything into it, check if the filled cells count strictly less than the size of the array (obviously you want to keep track of the array total size as well).

Java - accumulator variable not incrementing after each loop iteration

When a car departs, the number of times a car was moved inside the garage should be shown along with the car plate. The output I am currently getting shows everything just fine, but the number of moves remains at 0 for all cars. I am having trouble figuring how to increment the variable and show the accumulated value in the output. How can I fix it?
Car class
package garagetester;
public class Car
{
private String licensePlate;//stores the license plate of the car as a String
private int movesCount = 0;//stores the number of times the car has been
//moved
public Car(String licensePlate)//builds a Car object with
{
this.licensePlate = licensePlate;
}
public String getLicensePlate() {
return licensePlate;
}
public int getMovesCount() {
return movesCount;
}
public void incrementMovesCount(int movesCount) {
movesCount++;
}
}//end of Car class
Garage Class
package garagetester;
public class Garage {
private Car[] garage; //array, stores Car objects
private final int LIMIT = 10; //determines length of the garage array
private int count;//number of cars in garage
public Garage() {
garage = new Car[LIMIT];
//creates an array of 10 elements
//first index = 0, last index = 9
public String arrive(Car newCar) {
String str = ""; //stores the result of the ARRIVE operation
/* If the garage is empty, the first car to arrive is parked in
the first empty spot closest to the exit*/
if (count != LIMIT) {
garage[count] = newCar;
count++;
str = newCar.getLicensePlate() + " has been parked";
} else {
str = "Sorry, " + newCar.getLicensePlate() + " the garage is full.";
}
return str;
}//end of arrive()
public String depart(String plate) {
String str = ""; //stores the result of executing the operation
int moves =0; //stores the number of times a car has been moved
boolean found = false; //flag
for (int i = 0; i < count - 1; i++) //for all elements in the array
{
//check if car with that plate number is in the garage
if (plate.equals(garage[i].getLicensePlate()))
{
found = true; //car has been found
if (found)//if found=true
{
//for all cars ahead of it
for (int j = i + 1; j < count; j++)//check if count or count-1
{
moves += garage[j].getMovesCount();
garage[j].incrementMovesCount(moves);
}
//for all cars behind it
for (int k = i; k > 0; k--) //or k=i-1, check when debugging
{
//move all cars behind it one position up
garage[k] = garage[k - 1];
}
str = plate + " has departed." + "it has been moved " + moves
+ " times. ";
count--; //decrease the number of cars in the garage by 1
}
else
{
str = "Sorry " + plate + " is not in the garage.";
}
}
}//end of for loop
return str;//prints the value stored in str
} //end of depart()
} //end of Garage class
Garage Tester Class
package garagetester;
import java.io.*;
import java.util.Scanner;
public class GarageTester
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//Initializes an array of 10 Car objects
Garage newGarage = new Garage();
//initializes a Scanner object to read data from file
Scanner scan = new Scanner(new File("garage.txt"));
//while there is tokens in the file
while (scan.hasNext())
{
String plate = scan.next();//stores the plate number read from file
String action = scan.next();//stores the action read from file
//evaluate action
switch (action) {
//if action has the value "ARRIVE"
case "ARRIVE":
Car aCar = new Car(plate);//create a Car object
System.out.println(newGarage.arrive(aCar));//call arrive method
break;
//if action has the value "DEPART"
case "DEPART":
System.out.println(newGarage.depart(plate));//call the depart method
break;
} //end of switch case
}//end of while
}//end of main()
} //end of GarageTester class
In your increment method should be like this in Car.java;
public void incrementMovesCount() {
this.movesCount++;
}
Also fix the other usage of this method. There is no need to send any data to new value. Car object has a movesCount field. That means , it can increment the movesCount itself.
If you dont want to change method signature , use this;
public void incrementMovesCount(int newMovesCount) {
this.movesCount = newMovesCount; //--newMovesCount refers to your calculation
}
but be carefull when using the last solution, because you are sending param as ;
moves += garage[j].getMovesCount(); //this moves never set to 0. Just equal to zero in the first iteration.
garage[j].incrementMovesCount(moves);
This is wrong i think. Because i suppose you wants to increment all of car's position. If you wants to apply first solution of my post, just fix compile error. But if you wants to apply second solution, just change this part like ;
garage[j].incrementMovesCount(garage[j].getMovesCount()+1);
Your parameter movesCount is shadowing the class member movesCount. In the following mutator:
public void incrementMovesCount(int movesCount) {
// movesCount++; --> this is incrementing the parameter
// either remove the parameter `movesCount` from this mutator
// since it's not being used, or do the following
this.movesCount++; // --> this refers to the class member movesCount
}

How to shift elements in a 2D array of Strings

So I am working on an 8puzzle slide game and I am having some trouble. So lets say that my current state S is:
1 5 6
3 7 B
2 8 4
where B represents the blank space (which is why I am doing my 2D array in String type). So I am trying to call move methods which will ultimately move the B space either up,down,left,or right. I have already recorded the position of B, so in this case it would be [1,2]. I use this B location to see if I can make a valid move up (can't make it if B[0] = 0), valid move down (can't make it if B[0] = 2), valid move left (can't make it if B[1] = 0) or valid move right (can't make it if B[1] = 2). So now if I do have a valid move for lets say up, how would I go about implementing that move function? I don't know how exactly to replace the location of B in my S state with the one above it if everything is in String type.
public class EightPuzzle {
String[][] gameBoard = new String[3][3];
String[] bLocation = new String[2];
String board;
String dir;
/*public void ReadFromTxt(String file) throws FileNotFoundException, IOException {
String read;
FileReader f = new FileReader(file);
int i = 0;
int j;
BufferedReader b = new BufferedReader(f);
System.out.println("Loading puzzle from file...");
while((read = b.readLine())!=null){
if(read.length()==3){
for(j=0;j<3;j++){
board[i][j] = (int)(read.charAt(j)-48);
}
}
i++;
}
b.close();
System.out.println("Puzzle loaded!");
}*/
public String[][] setState(String board){
gameBoard[0][0] = board.substring(0,1);
gameBoard[0][1] = board.substring(1,2);
gameBoard[0][2] = board.substring(2,3);
gameBoard[1][0] = board.substring(4,5);
gameBoard[1][1] = board.substring(5,6);
gameBoard[1][2] = board.substring(6,7);
gameBoard[2][0] = board.substring(8,9);
gameBoard[2][1] = board.substring(9,10);
gameBoard[2][2] = board.substring(10,11);
System.out.println(Arrays.deepToString(gameBoard));
return gameBoard;
}
public String[][] randomizeState(){
return null;
}
public void move(String dir){
if(dir.equalsIgnoreCase("up")){
if(bLocation[0].equals("0")){
//cannot move up
}
else{
int[] temp;
}
}
if(dir.equalsIgnoreCase("down")){
if(bLocation[0].equals("2")){
//cannot move down
}
else{
}
}
if(dir.equalsIgnoreCase("left")){
if(bLocation[1].equals("0")){
//cannot move left
}
else{
}
}
if(dir.equalsIgnoreCase("right")){
if(bLocation[1].equals("2")){
//cannot move right
}
else{
}
}
}
public void bLocation(String board){
setState(board);
for(int i=0; i<gameBoard.length; i++){
for(int j=0; j<gameBoard[i].length; j++){
if(gameBoard[i][j].equals("b"))
{
bLocation[0] = Integer.toString(i);
bLocation[1] = Integer.toString(j);
}
}
}
}
public static void main (String[]args){
EightPuzzle b1=new EightPuzzle();
b1.setState("156 37b 284");
b1.bLocation("156 37b 284");
}
}
A shift upwards would mean swapping B with the the tile above it.
For code simplicity, make a method moveB which swaps two locations:
private void moveB(int deltaRow, int deltaCol) {
int newRow = bLocation[0] + deltaRow;
int newCol = bLocation[1] + deltaCol;
String temp = gameboard[newRow][newCol];
gameBoard[newRow][newCol] = gameBoard[bLocation[0]][bLocation[1]];
gameBoard[bLocation[0]][bLocation[1]] = temp;
bLocation[0] = newRow;
bLocation[1] = newCol;
}
To shift upwards: moveB(-1, 0);
To shift downwards: moveB(1, 0);
To shift left: moveB(0, -1);
To shift right: moveB(0, 1);

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.

Categories

Resources