I'm having issues with getting my code to print. I need to print a checker board with a grid the size of a user input.
Example of what it should output.
Input a size (must be larger than 1):
5
0 * * *
1 * *
2 * * *
3 * *
4 * * *
Here's my code:
import java.util.Scanner;
public class nestedpractice1
{
public static void main(String[] args)
{
Scanner kbinput = new Scanner(System.in);
//Create Size variable
System.out.println("Input a size: ");
int n = 0; n = kbinput.nextInt();
for(int r = 0; r < n; r++)
{
for(int c = 0; c < r; c++)
{
if((r%2) == 0)
{
System.out.print("*");
}
else if((r%1) == 0)
{
System.out.print(" *");
}
}
System.out.println("");
kbinput.close();
}
}
}
My code keeps printing
**
****
This loop yields precisely the output you specified:
for (int r = 0; r < n; r++) {
System.out.print(r);
for (int c = 0; c < n; c++) {
System.out.print(r % 2 == 1 ^ c % 2 == 0 ? " *" : " ");
}
System.out.println();
}
I condensed the body of the inner loop to a single print
statement. This statement uses the ^
(xor) operator to test for a condition, and then the ?:
(ternary) operator to print an asterisk if the condition is true
or spaces if the condition is false
.
We could break up that single statement, while retaining its meaning, like so:
boolean isOddRow = r % 2 == 1;
boolean isEvenCol = c % 2 == 0;
System.out.print(isOddRow ^ isEvenCol ? " *" : " ");
As explanation, we want to print a *
only if the row and column are both even or both odd. So if the row is even but the column is odd, or if the row is odd but the column even, we print only spaces.
We could express the same logic using ==
instead of ^
by:
boolean isEvenRow = r % 2 == 0;
boolean isEvenCol = c % 2 == 0;
System.out.print(isEvenRow == isEvenCol ? " *" : " ");
Or if you prefer the longhand if..else
over the shorthand ternary operator:
if (isEvenRow == isEvenCol) {
System.out.print(" *");
} else {
System.out.print(" ");
}