i have a board([17][17]) and i place words in it giving the row and the column.I want if the position of the word given is bigger than the board,then a message is shown and you should give the row and column again.
**Board class**
......
public void placeWord(char[][] board, String word, int x, int y)
for (int i = 0; i < word.length(); i++)
{
if (y + i >= board[x].length)
{
System.out.println("The board is smaller!!");
Board b=new Board();
int a,r;
System.out.println("Give row and column again");
a=in.nextInt();
r=in.nextInt();
b.placeWord(board, word, a, r);
}
else {
board[x][y + i] = word.charAt(i);
}
}
When i give a=3 and r=5 it still prints me "The board is smaller!!" and want to give new values again.Does anyone know how to fix this?
Edit
**main()**
board b=new board();
String s="abc";
int x=2,y=20;
b.placeWord(Board, s, x, y);
for(int i=0;i<Board.length;i++)//prints the board
{
System.out.println(Board[i]);
}
From a=3 and r=5 I suspect you already failed for placing the word in the first place and entered a new row/column.
In this case the "old" for loop has not finished yet and will continue to place letters (as long as there are some remaining) after the call to b.placeWord(...);.
One way to circumvent this is to break the loop by a simple break; statement after the call to b.placeWord(...);.
Note: the second time you are filling the word into your newly created board b which you discard afterwards (it is never accessed anywhere in the code you showed us). Additionally you might first test if the word fits (can actually be done without a loop: y+word.length()<=board[x].length()) and then fill in the letters. Otherwise the remainders of the failed attempt will stay on the board.
**Board class**
......
public void placeWord(char[][] board, String word, int x, int y)
if (y + word.length() >= board[x].length)
{
// don't loop, ask for another position to put word
System.out.println("The board is smaller!!");
Board b=new Board();
int a,r;
System.out.println("Give row and column again");
a=in.nextInt();
r=in.nextInt();
b.placeWord(board, word, a, r);
} else
{
// already done the checking, don't need to worry here
for (int i = 0; i < word.length(); i++)
{
board[x][y + i] = word.charAt(i);
}
}
Related
I am still new to Java and have been working with 2D arrays recently. What I am trying to do is make a simple 2D grid array of a Chessboard that has the arrays from a1 all the way to h8. The first thing I tried to do is convert the array [8][8] so that the first 8 was characters and the second 8 was integers. What I am currently trying to do is prompt the user and ask them which coordinate they would like to choose (from a1 all the way to h8). When they choose one of the coordinates, I would like them to enter a string (which in the future will be my chess pieces) that will be stored on the board, so that, when I use another class to print these strings, it'll give me an output like "a5 - Lemon (As im not checking to see if the chess piece is a valid piece yet) or "h2 - Queen".
So, to clarify, the program asks the user "Please enter a coordinate (e.g. a5)". "Now, Please enter a piece to be placed on that coordinate" Which then gets stored in that coordinate. When the user types, for example, "Done" I would like all the coordinates that have pieces on them to be revealed as well as what piece was put on them.
Code:
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
int[][] grid = new int [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int col = (int)(input.charAt(0) - 'a');
int row = (int)(input.charAt(1) - '0');
}
}
}
I have used a while loop to continuously prompt the user until they give a correct coordinate, but Im not sure how to prompt the user to enter a piece that gets stored in that coordinate?
Any help would be appreciated!
First of all, in order to store the piece name with the coordinates, you will need a 2D array of strings instead of integers.
After changing that, you take the user input again and then save the coordinates with the piece and save it in the 2d array at said column and row.
Also, the row is retrieved from the character (a-b-c-etc..) and the column from the number and not the way around.
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}
I have been working on a 1D Tic Tac Toe project for a while now, and I am still fairly new to coding, so I have a couple questions/issues.
To start off, I am having issues with printing the board as a 1D String array. Primarily setting it up in the three x three fashion with the 'blanks' represented as '-'.
//global variables
static int ArrayLength = 9;
static String[] board = new String[ArrayLength];
static int maxVal = ArrayLength;
static void PrntBoard()
{
for (int cntr = '-'; cntr < maxVal; cntr++)
{
System.out.println(board[cntr]);
}
}
I am also experiencing issues with my Computer Moves, as I keep getting errors with the computer unable to wrap around the array to eventually find an empty space and checking if a space is available in the first place.
static void CompMove() {
int space = 0;
//keep asking till they get an empty one
//have the comp random pick a spot
space = RNG.nextInt(9);
//check
while (board[space].equals('X') || board[space].equals('O'));
{
space = RNG.nextInt(9)-1;
}
//fill in the game board with the valid position
if (board[space].equals('-')) {
board[space].equals('O');
PrntBoard();
}
int lastspace = space;
}
Any help would be greatly appreciated, as I am still, quite frankly, a novice and do not possess much knowledge in coding. Thank you.
First, please take a look on Java Language Basic to learn some basic concept.
For the printBoard method, the for condition should start from 0 to maxVal, instead of using char '-', which is converted to int 45, check out Primitive Data Types for details.
For the CompMove method, the equals comparison fails as you are comparing String(board[space]) with Character('X'), which is of different types. Please note that 'X' is different to "X" in Java.
To fill in the game board with the valid position, board[space].equals('O'); is not what you need, equals only do the comparison and not setting value. Use board[space] = "O"); instead.
Please try the following code to verify the above points.
public static void main(String[] args) {
System.out.println("'-' converted to int is " + (int) '-');
System.out.println("\"X\".equals('X')? " + "X".equals('X'));
String[] board = new String[9];
for (int i = 0; i < 9; i++) {
board[i] = "-";
}
System.out.println("Before change\t" + Arrays.toString(board));
board[0] = "O";
System.out.println("After change\t" + Arrays.toString(board));
}
Finally, please try to follow the Java Naming Convention, method and variable name should start with lower case.
In First example you have error in for loop. Should be:
for(int cntr=0; cntr<board.length; cntr++) {
System.out.println(board[cntr]);
}
In your case int cntr='-' is this same as 'int cntr=92`(because you cast char '-' to int and char '-' is number 92) but you have initialized array with 9 positions length.
In second example you have to remove semicolon next to while loop. Should be:
while (board[space].equals('X') || board[space].equals('O')){
space = RNG.nextInt(9)-1;
}
in your case while (board[space].equals('X') || board[space].equals('O')); you will never get into brakets
Before asking my question I want to make some things clear. First, I am new to Java and programming in general. Second, This is my second post so please go easy on me if I did something wrong. Finally, I would like an explanation as to why what I did was wrong instead of just a pasted solution in any responses to this post. To better understand the issue I will write the assignment information, then the Driver class that is given, then my class code that is accessed by the Driver class.
My question:
How can I get the bottom left of my 'building' to be [0][0] on my 2D array? Here's an example of a for loop that works in changing the bottom left of a 2D array to [0][0], but I tried implementing this into my searchRoom method (where the player character is set to myHidingPlaces index) and I can't get myHidingPlaces[0][0] to be the bottom left of my 2D Array. I believe that i need to edit the toString method somehow with for loops, but I can't figure out how I should do it.
The following is the assignment:
You are to design a class “LostPuppy.java” which represents a puppy lost in a multi-floor building that
contains the same number of rooms on each floor. During instantiation (or creation) of an object of this class,
each room on each floor will be initialized as empty (you will actually use the space ‘ ‘ character for this
purpose) and a random room will be chosen where the puppy is lost. For this purpose, the character “P” will
be placed in this random location. Further details on the constructor is listed below.
An object of this class is used as a game for two players to take turns searching for the puppy, one room at a
time until the unfortunate little canine is found. The instantiation of this object and the search will be performed
by a “driver” program which has been provided to you allowing you to only have to concentrate on developing
the class (the driver program is in the file “PuppyPlay.java”)
Fields (of course, all fields are private):
A character (char) array named myHidingPlaces. This represents the building where the rows are floors
and the columns are rooms on each floor (this building has an unusual numbering system; the floors and
rooms both start at zero).
Two integers that will hold the floor and room where the puppy is lost, named myFloorLocation and
myRoomLocation.
A char named myWinner which will be assigned the player’s character when a player finds the puppy
(the driver program uses digits ‘1’ and ‘2’ to more clearly distinguish the players from the puppy).
A boolean named myFound which is set to true when the puppy is found.
Constructor:
Receives two integer parameters as the user’s input for the number of floors and rooms of the building
in which the puppy is lost.
The constructor instantiates the 2D array “myHidingPlaces” as a character array with the first parameter
for the rows (theFloors) and the second parameter as the columns (theRooms).
Initialize myHidingPlaces’ cells, each to contain a space ‘ ‘ (done with single quotes)
Set myFloorLocation (floor puppy is on) randomly based using the first parameter
Set myRoomLocation (room puppy is in) randomly based using the second parameter
Set myHidingPlaces[myFloorLocation][myRoomLocation] to the char ‘P’
Set myWinner to a single space
Set myFound to false
Methods:
roomSearchedAlready receives the floor and room to be searched and returns true if the room has
already been searched, false otherwise.
puppyLocation receives the floor and room to be searched and returns true if the floor and room are
where the puppy is lost, false otherwise. This method should NOT change any of the fields.
indicesOK receives the floor and room to be searched and returns true if the floor and room values are
within the array indices range, false otherwise (used to check that these indices will not cause an error
when applied to the array).
numberOfFloors returns how many floors are in the building (the first floor starts at zero).
numberOfRooms returns how many rooms are on each floor of the building (the first room starts at
zero and all floors have the same number of rooms).
searchRoom receives the floor and room to be searched and also the current player (as a char type)
and returns true if the puppy is found, false otherwise. If the puppy is NOT found searchRoom also
sets the myHidingPlaces array at the received floor and room location to the received player value (a ‘1’
or a ‘2’) OR, when found, sets the myWinner field to the current player AND sets myFound to true.
toString displays the current hidingPlaces array and it’s contents EXCEPT the location of the puppy
which remains hidden until he/she is found at which point toString will be called (by the driver) and both
the player who found the puppy and a ‘P’ will be displayed in the same cell….
NOW, and perhaps the awkward portion of the toString output. Normally, when displaying a 2D array,
the [0][0] cell is displayed in the upper left corner as with matrices. However, because the puppy
decided to get lost in a building and not a matrix, it would make more visual sense to have the first floor
(row 0) displayed on the bottom, second floor above it… and finally the top floor, well… on top! To
save words, look closely at the sample run provided on the next page. Your output should look the
same as what is seen on the next page in the sample run.
Here is the Driver program:
import java.util.Random;
import java.util.Scanner;
/**
* This program is used as a driver program to play the game from the
* class LostPuppy. Not to be used for grading!
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
* #author David Schuessler
* #version Spring 2015
*/
public class PuppyPlay
{
/**
* Driver program to play LostPuppy.
*
* #param theArgs may contain file names in an array of type String
*/
public static void main(String[] theArgs)
{
Scanner s = new Scanner(System.in);
LostPuppy game;
int totalFloors;
int totalRooms;
int floor;
int room;
char[] players = {'1', '2'};
int playerIndex;
boolean found = false;
Random rand = new Random();
do
{
System.out.print("To find the puppy, we need to know:\n"
+ "\tHow many floors are in the building\n"
+ "\tHow many rooms are on the floors\n\n"
+ " Please enter the number of floors: ");
totalFloors = s.nextInt();
System.out.print("Please enter the number of rooms on the floors: ");
totalRooms = s.nextInt();
s.nextLine(); // Consume previous newline character
// Start the game: Create a LostPuppy object:
game = new LostPuppy(totalFloors, totalRooms);
// Pick starting player
playerIndex = rand.nextInt(2);
System.out.println("\nFloor and room numbers start at zero '0'");
do
{
do
{
System.out.println("\nPlayer " + players[playerIndex]
+ ", enter floor and room to search separated by a space: ");
floor = s.nextInt();
room = s.nextInt();
//for testing, use random generation of floor and room
//floor = rand.nextInt(totalFloors);
//room = rand.nextInt(totalRooms);
} while (!game.indicesOK(floor, room)
|| game.roomSearchedAlready(floor, room));
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
} while (!found);
playerIndex = (playerIndex + 1) % 2;
System.out.println("Great job player " + players[playerIndex] +"!");
System.out.println("Would you like to find another puppy [Y/N]? ");
}
while (s.nextLine().equalsIgnoreCase("Y"));
}
}
Finally, here is my test code:
import java.util.Random;
import java.util.Scanner;
public class LostPuppy
{
int value;
char[][] myHidingPlaces;
int myFloorLocation;
int myRoomLocation;
char myWinner;
boolean myFound;
Random random = new Random();
public LostPuppy(int theFloors, int theRooms)
{
myHidingPlaces = new char[theFloors][theRooms];
for (int i = theFloors - 1; i >= 0; i--)
{
for (int j = 0; j <= theRooms - 1; j++)
{
myHidingPlaces[i][j] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
public boolean roomSearchedAlready(int floor, int room)
{
return (myHidingPlaces[floor][room] == '1' ||
myHidingPlaces[floor][room] == '2');
}
public boolean puppyLocation(int floor, int room)
{
return (myHidingPlaces[floor][room] == 'P');
}
public boolean indicesOK(int floor, int room)
{
return (floor <= myHidingPlaces.length && room <= myHidingPlaces[0].length);
}
public int numberOfFloors()
{
return myHidingPlaces.length - 1;
}
public int numberOfRooms()
{
return myHidingPlaces[0].length - 1;
}
public boolean searchRoom(int floor, int room, char player)
{
if (puppyLocation(floor, room))
{
myFound = true;
myWinner = player;
return true;
}
else
{
myHidingPlaces[floor][room] = player;
return false;
}
}
public String toString()
{
int rooms = myHidingPlaces[0].length;
int floors = myHidingPlaces.length;
System.out.print(" ");
for (int x = 0; x < rooms; x++)
{
System.out.print("___");
}
for (int y = 0; y < rooms - 1; y++)
{
System.out.print("_");
}
System.out.print("\n");
for (int r = 0; r < floors; r++)
{
System.out.print("| ");
for (int c = 0; c < rooms; c++)
{
if (myHidingPlaces[r][c] == 'P' && myFound)
{
System.out.print("" + myWinner + "" + myHidingPlaces[r][c] + "| ");
}
else if (myHidingPlaces[r][c] == 'P' && !myFound)
{
System.out.print(" | ");
}
else
{
System.out.print(myHidingPlaces[r][c] + " | ");
}
//System.out.print(myHidingPlaces[r][c] + " | ");
}
System.out.print("\n");
for (int i = 0; i < rooms; i++)
{
System.out.print("|___");
}
System.out.print("|\n");
}
return "";
}
}
There is no way you can make a reversed array in Java, but you don't need it. You need to think of the building and operate with it just like you would do it with matrices. However you need to print it upside-down. Also there is no changing of position in array by the link you provided, it is just an array traversal from last index to first.
So you need to print array upside-down and this is pretty easy. You need to change one line in your toString method, change
for (int r = 0; r < floors; r++)
to
for (int r = floors - 1; r >= 0; r--)
And you will get correct result!
Also in this case you don't need to fill array from last to first (at least because you fill it with the same value), like you do
for (int i = theFloors - 1; i >= 0; i--) {
for (int j = 0; j <= theRooms - 1; j++) {
...
}
}
It will be better if you do it like this (just better to read your code)
for (int i = 0; i < theFloors; i++) {
for (int j = 0; j < theRooms; j++) {
...
}
}
As #Dante said you also need to correct indicesOK method because last index of array is its length - 1, so when you access myHidingPlaces.length or myHidingPlaces[i].length element the exception ArrayIndexOutOfBoundsException will be thrown.
public boolean indicesOK(int floor, int room) {
return (floor < myHidingPlaces.length && room < myHidingPlaces[0].length);
}
I need to create a triangle of at least 5 rows.
I know how to create the top and bottom but I can't figure out the middle part. I don't know how to find the algorithms to express the changes in spaces added to each subsequent row following the first. Can I get hints?
This problem is from my teacher.
You can think as this: suppose you want to paint a triangle of R rows. Then, for example, for R = 5, you would paint something like this:
*
**
***
****
*****
which is isosceles (and also right :)). So, the basic observation is that if the current row has i stars, the previous has i-1 and the next one i+1. So, you can initialize a variable with the current row, which also holds the number of stars to paint. Something like this:
int R = (...) // get this parameter from user or whatever
int r = 1; // current row, and number of stars to paint in the current line
while (r <= R) { // while you haven't painted more than R rows
int i = 1; // counter for painting r stars
while (i <= r) {
System.out.print('*');
++i; // next star
}
System.out.println(); // go to the next row (or line)
}
Hope it helped.
Edit: if your teacher is as skeptical as RealSkeptic down there in the comments, you can use the following observation. Suppose you want to paint a triangle like this:
*
**
***
**
*
That is, an isosceles triangle rotated, such that the len of the equal sides is R. For the example, R = 3. You can see that painting such triangle is like painting a rectangle with 2 different kinds of cells, like the following:
*00 (1 star, 2 zeroes)
**0 (2 stars, 1 zero)
*** (3 stars)
**0 (2 stars, 1 zero)
*00 (1 star, 2 zeroes)
You can note that the sequence grows and then decreases back. You can simulate such behavior with a counter that starts in negative values and runs until the same positive value. The code would be something like:
int R = (...) // get this parameter from user or whatever
int r = -R+1;
while (r <= R-1) {
int i = 1;
int rabs = r;
if (rabs < 0) rabs = -rabs; // take only the positive value
while (i <= R-rabs) {
System.out.print('*');
++i; // next star
}
System.out.println(); // go to the next row (or line)
++r;
}
EDIT2: watching the triangle you added to your question (which you should have added since the very beginning), you can follow the reasoning of the previous edit on the number of stars and spaces per row, and reach to a code like the following:
int R = (...) // get this parameter from user or whatever
int r = 1;
while (r < R) {
int i = 1;
while (i <= R-r) {
System.out.print(" ");
++i;
}
if (r>1) System.out.print("*"); // because there's only 1 star on first row always
i = 1;
while (i <= 2*r-3) { // the amount of spaces you need to paint
System.out.print(" ");
++i;
}
System.out.println("*");
++r;
}
// paint the last row separately
int last = R+R-1;
while (last > 0) {
System.out.print("*");
--last;
}
Good luck.
EDIT3: maybe this approach is more verbose, but easier to understand. The point is to save in variables how many spaces you need to print before the first star, and after the first star, in each row. The code would be like this:
int R = (...) // get this number from user or whatever
int spacesBeforeFirstStar = R-1;
int spacesAfterFirstStar = -1;
int r = 1;
while (r <= R) {
int i = 1;
while (i <= spacesBeforeFirstStar) { // paint the first spaces
System.out.print(" ");
++i;
}
if (r!=1) System.out.print("*"); // if not the first row, paint the first star
i = 1;
while (i <= spacesAfterFirstStar) { // paint the spaces inside the triangle
if (r==R) // if we are in the last row
System.out.print("*"); // we paint stars instead spaces
else
System.out.print(" "); // otherwise, we just paint spaces
++i;
}
System.out.println("*"); // print the second star
spacesBeforeFirstStar -= 1; // in the next row, we paint one space less
spacesAfterFirstStar += 2; // in the next row, we paint two spaces more
++r; // go to the next row
}
Here,
int n = 6;
int row = 0;
int col = 0;
int space = 0;
for(row = 1; row < n; row++) {
for(space = 0; space < n - row; space++) {
System.out.print(" ");
}
for(col = 1; col <= row; col++) {
if(row == (n-1)) {
System.out.print("* ");
} else {
if(col == 1 || col == row) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
It prints out the following:
As you can see it's an equilateral triangle. You can modify the code in the loop using conditional statements so that when it reaches at the time of creating the base for the triangle it will print this
I have left that one for you to ponder upon.
I am currently trying to write a program where the user will input a string and then the program will output the occurrence of lowercase letters as such:
"Hello world! The quick brown fox jumps over the fence."
a:
b:*
c:**
d:*
e:*****
f:**
g:
h:***
... so on until z.
I just have no idea how to go about writing this. I've looked around but no one uses arrays. I was thinking you have an array for the alphabet and then have a loop that takes each element of the string and corresponds it with a letter of the alphabet, which then adds one to the counter which wil ultimately display the histogram.
Just not sure how to go about it.
Thanks.
EDIT: Here's what I have so far. It's not much and I still don't really understand what to do. But it's something.
import java.util.Scanner;
public class CountingChars {
public static void main(String[] args) {
System.out.println("Enter the text you would like to count the characters of. Please end with a blank line.");
Scanner sc = new Scanner(System.in);
String userInput = sc.nextLine();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int[] amount = new int[alphabet.length()];
//for (int i = 0; i < userInput.length();i++){
//}
char occurrence;
int count = 0;
while(userInput.length()>0){
occurrence = userInput.charAt(0);
int i = 0;
while(i < userInput.length() && userInput.charAt(i) == occurrence){
count++;
}
}
}
}
Two basic ways of doing this which come to mind.
First is using an array of fixed length with stored ints (lower alph chars), where 'a' is on index 0. And then iterate through the given chararray updating the specific index (you can get the index by something like 'selectedChar' - 'a', which will give you the index position). Then you simply iterate through the list a print number of asterisks accordingly.
Second way is using a HashMap, where you store per each character the value, count the chars, update the value in the map accordingly and then simply go through the map and print those out (now that I am thinking about it, SortedMap will be better).
public static void printAlphabetHistogram(String input) {
int amount[] = new int[25];
for(char c : input.toCharArray()) {
if(Character.isAlphabetic(c)) {
c = Character.toLowerCase(c);
amount[c - 'a'] += 1;
}
}
for(int i = 0; i < amount.length; i++) {
System.out.printf("%s:", (char)('a' + i));
for(int j = 0; j < amount[i]; j++) {
System.out.print("*");
}
System.out.println();
}
}