I have a two-dimensional character array board[row][col], which is designed to simulate a game board for a game of Xs and Os. (For reference, each element in the array is either an X, an O, or ' ', a space to signify no move in that square.)
I am trying to get a string of all characters in the array, row by row. That is, the first row will be printed to string, then the second row will be appended to that string, until all rows are traversed. In the end, the result should look like a string of symbols such as "XXO X OOX" for this game board:
X X O
X
O O X
How can this be done?
try:
StringBuilder str = new StringBuilder();
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
str.append(board[i][j]);
you could find more data about StringBuilder here.
I think better sulution will be like this
char [][] board = new char[][]{{'x','x','o',},{'x',},{'o','o','x',}};
StringBuilder builder = new StringBuilder();
for (char[] aBoard : board)
builder.append(String.valueOf(aBoard)).append(" ");
System.out.println(builder.toString());
out
xxo x oox
You can try something along these lines:
char[][] board = {{'X', 'O', 'X'}, {0, 'O', 0}, {'X', 'O', 'X'}};
String s = "";
for (char[] row : board) {
for (char c : row)
s += c == 0 ? " " : c;
s += "\n";
}
System.out.println(s);
Output:
XOX
O
XOX
Edit: If you want the output to be spaced out, you could use
for (char[] row : board) {
for (char c : row)
s += c == 0 ? " " : c + " ";
s += "\n";
}
Output:
X O X
O
X O X
for(int i=0; i< board.length; i++){
for(int j=0; i< board[i].length; j++){
System.out.print(""+board[i][j]); //<- use print() here
}
System.out.println(); //<- use println() here
}
Have nested loops like so:
for (int i = 0; i < board.length; i++)
{
for (int j = 0; j < board[0].length; j++)
{
System.out.print(board[i][j] + " ");
}
System.out.println();
}
The first print statement will add all the characters from one row together and then the next print statement, outside of the second loop, will append a newline.
String[][] board = {{"X", "X","O"},{" ", "X", " "},{"O", "O", "X"}};
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
Related
I need to print this:
I need to print this square using a for loop in java.
This is what I have so far:
public static void main(String [] args)
{
for(int i = 0; i < 5; i++){
System.out.print("O ");
}
System.out.println();
for(int i = 0; i < 4; i++){
System.out.print("O ");
}
}
The easiest solution would be to nest two loops, first print O then use a second loop to print .. You know that each line should have a decreasing number of O (and increasing number of .s). In fact, you have 5 - i and i of each per line (where i is row number). And you can use the outer loop to determine how many of each should be drawn with those formulae. Like,
int size = 5;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size - i; j++) {
System.out.print("O ");
}
for (int j = 0; j < i; j++) {
System.out.print(". ");
}
System.out.println();
}
Which outputs (as requested)
O O O O O
O O O O .
O O O . .
O O . . .
O . . . .
Another option would be to create a StringBuilder to represent the initial conditions, print and then mutate the StringBuilder. This uses additional storage, but eliminates the need for nested loops.
int size = 5;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append("O ");
}
for (int i = 0; i < size; i++) {
System.out.println(sb);
sb.setCharAt(sb.length() - (i * 2) - 2, '.');
}
And, you could also make that with an array of boolean(s) (e.g. a bitmask). Convert false to O and true to ., and set the last element offset by the index to true on each iteration. Like,
int size = 5;
boolean[] arr = new boolean[size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(arr[j] ? ". " : "O ");
}
System.out.println();
arr[size - i - 1] = true;
}
This is not a 'design pattern' problem. You just need to use the logic with loops.
Here's the logic.
In a square of n x n cells, the ith row contains (n-i) ovals and i
dots, where 0 <= i < n.
Refer to the other answer to see a working snippet.
For this assignment, after inputting any word, it will print it in a pattern shown below (in this case, the word is computer):
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Currently, my code is this:
String output = "";
for (int a = word.length()-1; a >= 1; a--)
{
for (int b = 0; b < word.length(); b++)
{
out.print(" ");
}
out.println(word.charAt(word.length()-1-a));
}
for (int c = 0; c < word.length(); c++)
{
out.print(word.charAt(word.length()-1-c));
}
out.print(word.substring(1));
return output + "\n";
The output for my code currently is:
C
O
M
P
U
T
E
RETUPMOCOMPUTER
Any advice or tips is much appreciated, thank you in advance!
The logic is simple, first try to create the last line, using reverse of StringBuilder. Then print each line from the first to the last line.
The last line case is simple.
From the first to the last line - 1, we only need to print those characters that has the distance equal 0, 1, 2 ... to the center of the last line.
public void printTriangle(String input) {
String tmp = input.substring(1);//Take the suffix
StringBuilder builder = new StringBuilder(tmp);
builder = builder.reverse().append(input);//Reverse, then append it
String line = builder.toString();//This is the last line
for(int i = 0; i < input.length(); i++){
for(int j = 0; j < line.length(); j++){
//Print the last line, or those that have distance equals i to the center of the last line
if(i + 1 == input.length() || Math.abs(j - line.length()/2) == i){
System.out.print(line.charAt(j));
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
Input
COMPUTER
Output
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Input
STACKOVERFLOW
Output
S
T T
A A
C C
K K
O O
V V
E E
R R
F F
L L
O O
WOLFREVOKCATSTACKOVERFLOW
You asked for nested loops, but there are a few other ways including padding it with spaces. If you are allowed to do that, you only need a single loop:
public static void printTriangle(String str){
int len = str.length()-1, idx = 1;
System.out.println(String.format("%"+(len+1)+"s", str.charAt(0)));
for(int x=0; x<str.length()-2; x++){
System.out.print(String.format("%"+(len--)+"s", str.charAt(idx)));
System.out.println(String.format("%"+(idx*2)+"s", str.charAt(idx++)));
}
System.out.println(new StringBuilder(str.substring(1)).reverse().toString() + str);
}
Output:
C
O O
M M
P P
U U
T T
E E
RETUPMOCOMPUTER
Instead of doing a code that will magically work for every case, try using a code that addresses every case:
String someString = "COMPUTER";
switch(someString.length()) {
case 0: System.out.println();
break;
case 1: System.out.println(someString);
break;
default:
int _spaces_before_after = someString.length()-1;
int _spaces_middle = 0;
for(int i=0; i<someString.length(); i++){
if(i!=someString.length()-1){
if(i==0){
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(0));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle = 1;
}
else {
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_middle; j++)
System.out.print(" ");
System.out.print(someString.charAt(i));
for(int j=0; j<_spaces_before_after; j++)
System.out.print(" ");
System.out.println();
_spaces_middle+=2;
}
_spaces_before_after-=1;
}
else {
for(int j=someString.length()-1; j>=0; j--)
System.out.print(someString.charAt(j));
for(int j=1; j<someString.length(); j++)
System.out.print(someString.charAt(j));
}
}
break;
}
Suppose you have a string str of length n. You'll have a matrix of size n × 2n+1.
First, you need to define the center c of your triangle, which would be the position n
In your first line of the matrix, you draw only the first letter (str[0]) in the center and then go to the next line.
In the second line, you draw the second letter (str[1]) in the positions c-1 and c+1.
In the third line, you draw the third letter (str[2]) in the positions c-2 and c+2.
And so on.
The last line is the trickier. Starting from the center c, you have to draw the whole word str. From the center, you start writing your string forwards and backwards.
I've tried some implementation, it's really simple:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int n = str.length();
char[][] matrix = new char[n][2*n+1];
char[] chrArr = str.toCharArray();
// initializes the matrix with blank spaces
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
matrix[i][j] = ' ';
}
}
// build the two sides of the triangle
for (int i = 0; i < n - 1; i++) {
matrix[i][n-i] = chrArr[i];
matrix[i][n+i] = chrArr[i];
}
// last line, build the base of the triangle
for (int i = 0; i < n; i++) {
matrix[n-1][n-i] = chrArr[i];
matrix[n-1][n+i] = chrArr[i];
}
// print
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*n+1; j++) {
System.out.print(matrix[i][j]);
}
System.out.print("\n");
}
Here is the sample code running in ideone.
You can try it with any string size.
I have this program im writing and i have to print just one column of a two dimensional array, not both.
for (int i = 0; i < sjf.length; i++)
{
for(int j = 0; j < sjf[i].length; j++)
{
System.out.printf("%5d%4s ", sjf[i][j], "|");
}
System.out.println();
}
System.out.println();
For example you want to print the fifth column:
int column = 5;
for (int[] row : sjf) {
System.out.printf("%5d%4s ", row[column], "|");
}
System.out.println();
Is it that what you need:
int j = <column_nr>;
for (int i = 0; i < sjf.length; i++)
{
System.out.printf("%5d%4s ", sjf[i][j], "|");
System.out.println();
}
System.out.println();
Just don't use the inner for loop.
int colToPrint = 1;
for (int i = 0; i < sjf.length; i++)
{
System.out.printf("%5d%4s ", sjf[i][colToPrint], "|");
System.out.println();
}
Here I've printed the second column i.e with index 1.
Is this what you want?
given the array sjf as an example
int sjf[][]={{1, 3, 5}, {5, 7, 7}};
for(int i = 0; i < sjf.length; i++){
for(int j = 0; j < sjf[i].length; j++)
{
System.out.printf("%5d%4s \n", sjf[i][j], "|");
}
//System.out.println();
}
System.out.println();
OUTPUT
1 |
3 |
5 |
5 |
7 |
7 |
for (int i = 0; i < sjf.length; i++)
{
for(int j = 0; j < sjf[i].length; j++)
{
if(j==1)//in case second column is printed out
System.out.printf("%5d%4s ", sjf[i][j], "|");
}
System.out.println();
}
System.out.println();
used an advanced for loop:
// local variable to hold the column we wish to print
int colToPrint = 2;
for (int row : sjf[colToPrint-1]) {
System.out.printf("%5d%4s%n", row, "|");
}
I am using Java and working on 5X5 board game(represented as String[][]) and I looking for an efficient way to randomly place 3 "A"'s, 3 "B",s 3 "C"'s, 3 "D"'s on the board.
I thought about using a nested for loop inside of a while loop to go over each slot, and randomly assign letters to 'slots' on the board, but I want to possibly do it in one pass of the board, if there is a good way to randomly place all 15 letters on the board in one pass.
Any suggestions?
You can use an ArrayList to store the letters (and the empty cells, I'm using a dot . so you can recognize it in the output), then use Collections.shuffle() to put elements of the ArrayList in "random" places. Finally assign each letter to the String[][] array:
public static void main(String[] args)
{
String[][] board = new String[5][5];
List<String> letters = new ArrayList<>();
// fill with letters
for (int i = 0; i < 3; i++) {
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");
}
// fill with "empty"
for (int i = 0; i < 10; i++) {
letters.add(".");
}
Collections.shuffle(letters);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
board[i][j] = letters.get(i*board.length + j);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
Output Sample:
C B . . .
A E . E A
. A . D D
C . . . D
B C E . B
Note:
The operation i*board.length + j will generate consequent numbers 0, 1, 2, 3, ... 24 en the nested loop.
One way: create an ArrayList<Character> or of String, feed it the 15 letters, call java.util.Collections.shuffle(...) on the ArrayList, and then iterate over this List, placing its randomized items into your array.
e.g.,
List<String> stringList = new ArrayList<String>();
for (char c = 'A'; c <= 'E'; c++) {
for (int i = 0; i < 3; i++) {
stringList.add(String.valueOf(c));
}
}
for (int i = 15; i < 25; i++) {
stringList.add(null);
}
Collections.shuffle(stringList);
String[][] gameBoard = new String[5][5];
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
gameBoard[i][j] = stringList.get(i * gameBoard.length + j);
}
}
// now test it
for (int i = 0; i < gameBoard.length; i++) {
for (int j = 0; j < gameBoard[i].length; j++) {
System.out.printf("%-6s ", gameBoard[i][j]);
}
System.out.println();
}
Thank you for reading,
essentially I have a matrix of Boolean values and to print them I am using:
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++) {
System.out.print(" " + matrix[r][c]);
}
System.out.println("");
}
I have tried and failed an obnoxious amount of times to replace the boolean values with chars, for example, replacing each false with the letter "x" and true with a "y", so that rather than a printed line read "false true true false true" it would read "x y x x y x"
-thank you for your time
You can use "? :" operator, follow this link http://www.cafeaulait.org/course/week2/43.html
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[0].length; c++) {
System.out.print(" " + (matrix[r][c] ? "y" : "x"));
}
System.out.println("");
}
You just need to add an if statement in the loop like:
if(matrix[r][c]){
System.out.print(" y");
} else {
System.out.print(" x");
}
Just use an inline if statement if it's just for output...
System.out.print((matrix[r][c]) ? "y" : "x");
m