while(!paths.isEmpty()){
BoggleSearchState2 path = paths.pop();
if(dictionary.contains(path.getWord()) && !foundWords.contains(path.getWord())){
foundWords.add(path.getWord());
}
int[][] grid = path.getGrid();
int row = path.getRow();
int column = path.getColumn();
Letter[][] game = path.getGame();
if(row < (grid.length-1) && grid[row+1][column] == 0) {
paths.push(new BoggleSearchState2(path.getWordWord(), game[(row+1)][column], game));
}
}
My BoggleSearchState2 constructor is overloaded like this:
public BoggleSearchState2(Letter l, Letter[][] gameIn) {
game = gameIn;
word = new Word(l);
grid = initialGrid(l);
row = l.getPoint().y;
column = l.getPoint().x;
stringWord = wordToString(word);
}
public BoggleSearchState2(Word wordIn, Letter l, Letter[][] gameIn){
game = gameIn;
word = new Word(wordIn.getLetters());
word.addLetter(l);
grid = genGrid(word, game);
row = l.getPoint().y;
column = l.getPoint().x;
stringWord = wordToString(word);
}
With my class variables like this:
public class BoggleSearchState2 {
private Word word;
private Letter[][] game;
private int[][] grid;
private String stringWord;
private int row, column;
The problem i am having is that after i push the new BoggleSS2, my path.word changes and adds another letter object. i do not know how this is happening. can anyone tell me why?
public class Word {
private ArrayList<Letter> word;
public Word(Letter l) {
word = new ArrayList<Letter>();
word.add(l);
}
public Word(ArrayList<Letter> listLetters, Letter l){
word = listLetters;
word.add(l);
}
public Word(ArrayList<Letter> letters) {
word = letters;
}
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I want to have two constructors in one class but I can't. I know it is possible but I can't find my mistake.
public static class Matrix{
int [][] matrix;
int row;
int column;
String matrixName;
Matrix (String [] input, String name) {
matrixName = name;
column = input.length;
row = input[0].split(",").length;
matrix = new int [row][column];
initialize(input);
}
Matrix (Matrix A, char ch) {
if (ch == 'T'){
column = A.row;
row = A.column;
}
else{
column = A.column;
row = A.row;
}
matrix = new int[row][column];
matrixName = "result";
}
the second Matrix can't be defined as a constructor.
There is no problem with the second constructor. The problem is with the first line of the declaration which is public static class Matrix. Note that you can not use static modifier here. Only public, abstract and final are allowed.
After this correction, you can test your class as follows:
class Matrix {
int[][] matrix;
int row;
int column;
String matrixName;
Matrix(String[] input, String name) {
matrixName = name;
column = input.length;
row = input[0].split(",").length;
matrix = new int[row][column];
// initialize(input);
System.out.println("First");
}
Matrix(Matrix A, char ch) {
if (ch == 'T') {
column = A.row;
row = A.column;
} else {
column = A.column;
row = A.row;
}
matrix = new int[row][column];
matrixName = "result";
System.out.println("Second");
}
}
public class Main {
public static void main(String[] args) {
Matrix m1 = new Matrix(new String[] { "a", "b" }, "Hello");
Matrix m2 = new Matrix(m1, 'X');
}
}
Output:
First
Second
Is it nested class in another class? Because class can be static only when it is nested in another class like this:
public class Matrix {
public static class NestedClass {
int number;
String string;
public NestedClass(NestedClass A, String string) {
this.number = A.number;
this.string = string;
}
public NestedClass(NestedClass A) {
this.string = A.string;
}
}
}
Class Matrix cannot be static, only final or abstract.
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;
So I am trying to add a cellType into a 2D array. The input from the file looks like a 6x6 file where it can be any combination of the enum type in my enum class below. For some reason when I try to troubleshoot the program, only WALL is getting added into my 2D array. I'm thinking there might be an error in my where I am trying to iterate through the 2D array, but I can't see it.
Here is where I am trying to add it within my 2D array
MazeCell.CellType[][] cell;
int rows = 6;
int cols = 6;
MazeCell.CellType cell2Add;
while(inputFile.hasNext())
{
String mazeStart = inputFile.nextLine().trim();
String [] mazeRowsAndCols = mazeStart.split(" ");
//System.out.println(mazeStart);
//System.out.println(mazeRowsAndCols[2]);
MazeCell.CellType cell2Add;
for(int r = 1; r < rows+1; r++)
{
System.out.print(r-1);
for(int c = 1; c<cols+1; c++)
{
if(mazeRowsAndCols[r-1].equals("W"))
{
cell2Add = MazeCell.CellType.WALL;
}
else if(mazeRowsAndCols[r-1].equals("M"))
{
cell2Add = MazeCell.CellType.START;
}
else if (mazeRowsAndCols[r-1].equals("C"))
{
cell2Add = MazeCell.CellType.END;
}
else if (mazeRowsAndCols[r-1].equals("O"))
{
cell2Add = MazeCell.CellType.OPEN;
}
else if (mazeRowsAndCols[r-1].equals(" "))
{
cell2Add = MazeCell.CellType.CURRENT_PATH;
}
else if (mazeRowsAndCols[r-1].equals("S"))
{
cell2Add = MazeCell.CellType.END_FOUND;
}
else if (mazeRowsAndCols[r-1].equals("X"))
{
cell2Add = MazeCell.CellType.REJECTED;
}
System.out.print(c);
cell[r-1][c-1] = cell2Add;
}
System.out.println();
}
}
}
inputFile.close()
Here is my enum class.
public class MazeCell
{
public static enum CellType
{
WALL("W"), START("M"), END("C"), OPEN("O"), CURRENT_PATH(" "), END_FOUND("S"), REJECTED("X");
private final String display;
private String type;
CellType(String display)
{
this.display = display;
}
public String getDisplay() { return display;}
public void setType(String type){this.type = type;}
};
What the input file looks like:
W W W W W W
W W M W W W
W W O O O W
W O W O O W
W W C O O W
W W W W W W W
W W W W W W
within cel[][] all I seem to be getting is Wall,
(mazeRowsAndCols[r-1].equals("S"))
you are using OUTER index to iterate over INNER elements (input line length). Try
(mazeRowsAndCols[c-1].equals("S"))
Moreover I would rather use switch for that (yes it is possible with string).
Besides I don't like the fact that you have outer for as this should be limited by input lines so while should be more then enough.
So in fact it should be something like that:
int row=0;
while(input.hasNext()){
String line=input.nextLine();
String parts[]=input.split(" ");
for(int c=0;c<parts.length;c++){
element=parts[c];
switch(element){
case W: enumToAdd=WALL; break;
case ......
///////////do the magic with `switch` here
}
maze[r][c]=enumToAdd;
}
row++;
}
public static CellType[][] read(Scanner scan) {
final int totalRows = 6;
final int totalColumns = 6;
CellType[][] maze = new CellType[totalRows][totalColumns];
for (int row = 0; row < totalRows; row++) {
String line = scan.nextLine();
for (int col = 0; col < totalColumns; col++)
maze[row][col] = CellType.parseId(line.charAt(col));
}
return maze;
}
public enum CellType {
WALL('W'),
START('M'),
END('C'),
OPEN('O'),
CURRENT_PATH(' '),
END_FOUND('S'),
REJECTED('X');
private final char id;
CellType(char id) {
this.id = id;
}
public static CellType parseId(char id) {
for (CellType type : values())
if (type.id == id)
return type;
throw new EnumConstantNotPresentException(CellType.class, String.valueOf(id));
}
}
I would suggest a few changes to make this a little easier to reason about.
First, let's fix up cell type a little to make it easier to use:
We should add a static fromDisplay(String s) method.
We should probably remove setType, because any call to setType will set that variable for that enum value everwhere, as there is only ever one instance of an enum value.
The resultant code is
public class MazeCell
{
public static enum CellType
{
WALL("W"),
START("M"),
END("C"),
OPEN("O"),
CURRENT_PATH(" "),
END_FOUND("S"),
REJECTED("X");
static {
final Map<String, CellType> fDisplay = new HashMap<>();
for(final CellType c : CellType.values()) {
fDisplay.put(c.display, c);
}
fromDisplay = fDisplay;
}
private static final Map<String, CellType> fromDisplay;
private final String display;
CellType(String display)
{
this.display = display;
}
public String getDisplay() { return display; }
public static CellType fromDisplay(final String display) {
return fromDisplay.getOrDefault(display, REJECTED);
}
}
}
Now, let's fix up the code. The problem is, as pointed out, that you only parse the first line every time. Let's fix that and clean up the code a little, too.
// Read our input in a try-with-resources
try(final File file = ...) {
final Scanner input = new Scanner(file);
// initialize the array
final MazeCell.CellType[][] cells = new MazeCell.CellType[6][6];
// assuming there are 6 rows
for(int r=0; r<6; r++) {
if(!input.hasNext()) throw new RuntimeException("Input file does not match our expectations! Only " + (r) + " lines!");
// assuming the columns are separated by spaces
final String[] cols = input.nextLine().trim().split(" ");
if(cols.length != 6) throw new RuntimeException("Input file does not match our expectations! Row " + (r + 1) + " had " + cols.length + " columns!");
for(int c=0; c<6; c++) {
cells[r][c] = MazeCell.CellType.fromDisplay(cols[c]);
}
}
// print it out or whatever
Arrays.stream(cells).map(Arrays::toString).forEach(System.out::println);
}
That should do it. Hope this helps!
Basically each room has a size of 10 by 10, the "W" represents the Walls, and the blank spaces -" " represent the Floor, and the numbers are Doors.I figured the best way to create the room is to create a method that receives a file and reads it and put its "information" into a String[10][10], and then create another method(or just do it in my Main) that receives the String[10][10] created and creates the room(adds the images to the room), but i am having some difficulties reading the file so if you guys could help me with that part i would be thankful.
Here is the type of text files from which i want to create my room:
WWWW0WWWWW
W W
W W
W W
W W
W WW
W WW
W WW
W W1
WWWWWWWWWW
Here are the Door, Wall and Floor classes:
public class Door implements ImageTile {
private Position position;
public Door(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Door";
}
#Override
public Position getPosition() {
return position;
}
}
public class Floor implements ImageTile {
private Position position;
public Floor(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Floor";
}
#Override
public Position getPosition() {
return position;
}
}
public class Wall implements ImageTile {
private Position position;
public Wall(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Wall";
}
#Override
public Position getPosition() {
return position;
}
}
And this is my method for adding images to my frame:
public void newImages(final List<ImageTile> newImages) {
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
images.addAll(newImages);
frame.repaint();
}
If you guys could help me i would appreciate it very much, thanks guys.Her is what i have now:
public class Room {
private String[][]room;
public Room(){
room = new String[10][10]; }
public static Room fromFile(File file){
if(file.exists()){
Scanner sc = null;
Room room = new Room();
try {
sc = new Scanner(file);
while(sc.hasNextLine()){
if(sc.nextLine().startsWith("#"))
sc.nextLine();
else{
String[] s0 = sc.nextLine().split("");
//Here is where my trouble is, i dont know how to add the content of this String s0 to the String s
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
} catch (FileNotFoundException e) {
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. "); }
finally{
if(sc!=null)sc.close();
}
}
else
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. ");
return null;
}
Each call to sc.nextLine() is reading another line from your file. You need to save the line into a temporary variable, and then refer to that temporary.
Maintain a counter of lines you've processed, so you can fill in the appropriate line in your s[][] matrix.
You only need to allocate storage for the 10 rows, since splitting the line you read in will result in an array of strings (the columns in one row) being allocated for you.
int row = 0;
String[][] s = new String[10][];
while(sc.hasNextLine() && i < 10) {
String line = sc.nextLine();
if( !line.startsWith("#")) {
String[] s0 = sc.line.split("");
s[row] = s0;
row++;
}
}
BTW, Use String[][] is overkill; since each string will only hold one character. Perhaps you could consider using char[][]. And line.toCharArray() would split the line into a char[] for you.
EDIT: (Due to edit of your question's code)
Instead of:
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
}
you want:
if(s0.length==10){
for(int y = 0; y < 10; y++){
s[row][y] = s0[y];
}
row++;
}
With row being the row counter in my above code.
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.