Java: Replacing Boolean with a Char - java

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

Related

How to output a hyphen after each character with restrictions using nested for loops in java

I just have one small issue with outputting a hyphen after every character (including the three dots shown in the code below)
Sample input
2 (option #)
disappear (phrase)
Expected output:
d-i-s-a-p-p-e-a-r-.-.-.
d-i-s-a-p-p-e-a-.-.-.
d-i-s-a-p-p-e-.-.-.
d-i-s-a-p-p-.-.-.
d-i-s-a-p-.-.-.
d-i-s-a-.-.-.
d-i-s-.-.-.
d-i-.-.-.
d-.-.-.
.-.-.
.-.
.
It outputs the "-" after every character excluding the last dot
I got the "-" to display after very word character but cant figure out displaying after the dots too, like it works but there has to be one less hypen:
My actual output:
d-i-s-a-p-p-e-a-r-.-.-.-
d-i-s-a-p-p-e-a-.-.-.-
d-i-s-a-p-p-e-.-.-.-
d-i-s-a-p-p-.-.-.-
d-i-s-a-p-.-.-.-
d-i-s-a-.-.-.-
d-i-s-.-.-.-
d-i-.-.-.-
d-.-.-.-
.-.-.-
.-.-
.-
I am partially done, I just need one less hyphen which would automatically also fulfill the requirement of not displaying a hyphen after the very last dot.
Code:
else if (option == 2){
for (int x = 0; x < phrase.length(); x++){
for (int y = 0; y < phrase.length() - x; y++){
char n = phrase.charAt(y);
System.out.print(n+"-");
}
for (int a = 0; a < 3; a++){
System.out.print("."+"-");
}
System.out.println("");
}
for (int j = 0; j < 3; j++){
for (int i = 0; i < 3 - j; i++){
System.out.print("."+"-");
}
System.out.println("");
}
}
One way you could remove the last - is to only print - when it's not the last iteration. You can check that it's not the last iteration by checking loopVariable != loopBound - 1.
So your code would be:
for (int x = 0; x < phrase.length(); x++){
for (int y = 0; y < phrase.length() - x; y++){
char n = phrase.charAt(y);
System.out.print(n+"-");
}
// You could just print the literal "--.-." instead
for (int a = 0; a < 3; a++){
System.out.print(".");
if (a != 2) { // Notice here!
System.out.print("-");
}
}
System.out.println();
}
for (int j = 0; j < 3; j++){
for (int i = 0; i < 3 - j; i++){
System.out.print(".");
if (i != 2 - j) { // and here
System.out.print("-");
}
}
System.out.println();
}
Here's how I would do it:
// pretend that the phrase is 3 characters longer than it actually is...
// because of the three dots at the end
for (int x = 0; x < phrase.length() + 3; x++){
for (int y = 0; y < phrase.length() + 3 - x; y++){
char n;
// Should we print the phrase or the dots?
if (y < phrase.length() - x) {
n = phrase.charAt(y);
} else {
n = '.';
}
System.out.print(n);
if (y != phrase.length() + 2 - x) { // same trick of checking if it is last iteration
System.out.print("-");
}
}
System.out.println();
}

Using For Loop to Print Pattern in Java

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.

How to output an ASCII star patterns in a table format?

I need help with my code issue. I have to write a program that displays a star pattern in a table format.
I am not exactly looking for the exact code, I would like to figure it out myself, so any suggestions and tips would be greatly helped.
// Pattern A Loop
for (int PatternA = 0; PatternA <= 9; PatternA++) { // outerLoop Pattern A
for (int PatternAI = 0; PatternAI <= PatternA; PatternAI++) { // Inner Loop
System.out.print("+");
}
System.out.println();
}
// Pattern B Loop
for (int PatternB = 0; PatternB <= 10; PatternB++) { // outer loop Pattern B
for (int PatternBI = 9; PatternBI >= PatternB; PatternBI--) { //Inner Loop
System.out.print("+");
}
System.out.println();
}
Since you said you don't want a full solution, here are some tips.
First, since your table will have to print material from both PatternAI and PatternBI on the same line, you should move those loops together. This will involve making the outer loop work for both. You can use more than one variable in a for loop:
for (int i = 0, j = 0; i < 10 && j < 2; i++, j++)
You also need some way to separate the patterns. You can use spaces, but they will vary in number (in fact the same way the +'s do, so you can use that). Tabs also work and are a bit simpler. You will have to change between the number of tabs you use when the line gets a certain length however.
That's about all there is to it. Let me know if my hints were helpful, or if there is a better way to phrase them.
Here's the full code, if you get stuck:
// Pattern is used for both PatternA and PatternB in this outer loop
// Outer Loop
for (int Pattern = 0; Pattern <= 9; Pattern++) {
// Inner Loop PatternA
for (int PatternAI = 0; PatternAI <= Pattern; PatternAI++) {
System.out.print("+");
}
if (Pattern < 7)
System.out.print("\t\t");
else
System.out.print("\t");
// Inner Loop PatternB
for (int PatternBI = 9; PatternBI >= Pattern; PatternBI--) {
System.out.print("+");
}
System.out.println();
}
The outer loop passes through the lines of the pattern and the inner loop passes through the elements of these lines. To combine multiple lines into one, you have to combine multiple inner loops within one outer loop.
Try it online!
For example, take these patterns:
Multiple inner loops within one outer loop:
int n = 5;
for (int i = -n; i <= n; i++) {
System.out.print(i == -n ? "a) " : " ");
for (int j = -n; j <= n; j++) {
if (i + j <= 0)
System.out.print("*");
else
System.out.print("-");
}
System.out.print(i == -n ? " b) " : " ");
for (int j = -n; j <= n; j++) {
if (i + j >= 0)
System.out.print("*");
else
System.out.print("-");
}
System.out.print(i == -n ? " c) " : " ");
for (int j = -n; j <= n; j++) {
if (i <= j)
System.out.print("*");
else
System.out.print("-");
}
System.out.print(i == -n ? " d) " : " ");
for (int j = -n; j <= n; j++) {
if (Math.abs(i) + Math.abs(j) <= n)
System.out.print("*");
else
System.out.print("-");
}
System.out.println();
}
Output:
a) *********** b) ----------* c) *********** d) -----*-----
**********- ---------** -********** ----***----
*********-- --------*** --********* ---*****---
********--- -------**** ---******** --*******--
*******---- ------***** ----******* -*********-
******----- -----****** -----****** ***********
*****------ ----******* ------***** -*********-
****------- ---******** -------**** --*******--
***-------- --********* --------*** ---*****---
**--------- -********** ---------** ----***----
*---------- *********** ----------* -----*-----
See also: How to print ASCII patterns in C# but using Java syntax?

Triangle Word Pattern using Nested Loops in Java

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.

Writing the contents of an array to a string

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();
}

Categories

Resources