java checkerboard pattern with asterisks - java

I've looked over lots of posts already and they have helped a lot, but none have covered my issue. I'm trying to print out an alternating checkerboard pattern for a class assignment. My output starting on the first line and every odd line has an extra print at the end. It should be repeating a 8x8 pattern basically. Here is my code and a screenshot of my output.
I need to know how to alter the code so that I only get 8 asterisks in the odd lines instead of the 9 that are showing now.
public class Checkerboard {
public static void main(String[] args) {
int length = 16;
int height = 8;
for (int i = 0; i <= height; i++)
{
if (i % 2 == 0)
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
for (int j = 0; j <= length; j++)
{
if (j % 2 == 0)
{
System.out.print(" ");
}
else
{
System.out.print("* ");
}
}
System.out.println("");
}
}
}
output

This works for me. I changed the last else statement to an else if with the condition j != length || i % 2 != 0 so now if it is an odd number row it will not print out an extra '*' at the end.
public class mainTest {
public static void main(String[] args) {
int length = 15;
int height = 8;
for (int i = 0; i <= height; i++)
{
if (i % 2 == 0)
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
for (int j = 0; j <= length; j++)
{
if (j % 2 == 0)
{
System.out.print(" ");
}
else if (j != length || i % 2 != 0)
{
System.out.print("* ");
}
}
System.out.println("");
}
}
}

Although below snippet is not optimized, but it should work for you. There is scope of simplification. Try that.
public static void main(String[] args) {
int length = 16;
int height = 8;
for (int i = 0; i <= height; i++) {
char first = ' ';
char second= '*';
if (i % 2 == 0) {
first = '*';
second = ' ';
}
for (int j = 0; j < length; j++) {
if (j % 2 == 0) {
System.out.print(first);
} else {
System.out.print(second);
}
}
System.out.println("");
}
}

Related

How to find common numbers or an anomaly in a 2D array and cause it to trigger something else

I have a 2D array (a matrix of 10x10) with values ranging from 0 to -5.
I want a method to be triggered when there is a sequence of a value found within the array.
For example, there is a sequence of two negative 2. I want it to trigger an event/method that will give a bonus score of 4. This should happen only when there are two -2's and not if there is just one -2.
I tried achieving something like that but I cant figure out how to tell the program to only trigger when 'n' number of a value is found within the matrix.
public class Test {
static int board[][] = new int[10][10];
public static void Test() {
int i, j;
board[0][0] = -1;
board[0][1] = -1;
board[1][1] = -2;
board[1][2] = -2;
board[1][3] = -2;
board[1][4] = -2;
for (i = 0; i < board.length; i++) {
System.out.println("");
for (j = 0; j < board.length; j++) {
//board[i][j] = 0;
System.out.print(board[i][j]);
}
}
System.out.println();
}
public static void scanBoard() {
int i, j;
for (i = 0; i < board.length; i++) {
for (j = 0; j < board.length; j++) {
if (board[i][j] == -1) {
System.out.println("Hello");
}
}
}
}
public static void main(String[] args) {
Test(); //prints out whole array
scanBoard(); //scans for
}
}
public class Main {
static final int size = 10;
static int[][] matrix = new int[size][size];
public static void main(String[] args) {
System.out.println("The first matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 3 && j > 3) {
matrix[i][j] = -2; //-2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
System.out.println("\nThe second matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 9 && j > 5) {
matrix[i][j] = 2; //changed it from -2 to 2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
}
static void scanBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == -2 && (j + 3 < size)) {
if (matrix[i][j + 1] == -2 && matrix[i][j + 2] == -2 && matrix[i][j + 3] == -2) {
System.out.println("\nThere you go, a special effect!".toUpperCase());
}
}
}
}
}
}
I am not sure if this is the result you wished to see according to your request. I hope this helps you. And I did some changes in your code so it will be easier to read (In my opinion lol).
public class Main {
static final int size = 10;
static int[][] matrix = new int[size][size];
public static void main(String[] args) {
System.out.println("The first matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 9 && (j == 0 || j == 1)) {
matrix[i][j] = -2; //-2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
System.out.println("\nThe second matrix.\n");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == 8 && (j == 5 || j == 6)) {
matrix[i][j] = 2; //changed it from -2 to 2
} else {
matrix[i][j] = 1;
}
System.out.print(matrix[i][j]);
}
System.out.println();
}
scanBoard();
}
static void scanBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (matrix[i][j] == -2 && (j + 1 < size)) {
if (matrix[i][j + 1] == -2) {
//You can remove the '.toUpperCase()', it's just my personal preference
System.out.println("\nThere you go, a special effect!".toUpperCase());
}
}
}
}
}
}
From what I understood from the problem statement and comments, you want your scanBoard to behave like this:
public static void scanBoard(int value, int frequency) {
int i, j;
if (value <= 0 && value >= -5 && frequency >= 2 && frequency <= 10) {
for (i = 0; i < board.length; i++) {
int rowFrequency = 0;
for (j = 1; j < board.length; j++) {
if (board[i][j] == value && board[i][j - 1] == value) {
rowFrequency++;
} else {
rowFrequency = 0;
}
if (rowFrequency + 1 >= frequency) {
System.out.println("Hello");
}
}
}
}
}
public static void main(String[] args) {
Test(); //prints out whole array
scanBoard(-2, 4); //prints Hello once
scanBoard(-2, 3); //prints Hello twice
scanBoard(-2, 3); //prints Hello thrice
}

Combine 2 2D arrays that both contain chars with java

I have to write a code as a task for my university and we have to recreate Minesweeper with java and it has to be runned in the command line.
For the matchfield we have to make an array that looks in the end like this picture:
Example how it sould look in the end
And to choose the field we have to use the scanner.
For example if you want to chose field C3, you have to type into the scanner C3.
At the moment im struggleing a little bit with the field.
I had 2 ideas but both didn't work out very well.
in the first try i tried to create everything with 2 for loops and 1 array but my problem was that I couldn't add 2 charrs, so I had the chars 0 to 9 and the charrs A to J.
In the second try I created 3 array, one with the numbers 0 to 9 and anothe array A to J and in the third array i wanted to combine both arrays. And now I'm wondering if this it's possible if I can acctually combine them in the way I want and if it's possible could somebody give me some help?
import java.util.Scanner;
import java.util.Arrays;
public class Minesweeper {
public static void main (String[] args) {
char c = 'A';
char d = '0';
char e = '9';
char f = 'J';
char[][] feldz = new char[11][11];
char[][] feldb = new char[11][11];
char[][] feld = new char[11][11];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldz[i][j] = ' ';
System.out.print(feldz[i][j] + " |");
}
if (d > e) {
d = '0';
}
if (d <= e && i > 0){
feldz[i][j] = d;
System.out.print(feldz[i][j] + " |");
}
if (i > 0 && j == 10) {
d++;
}
}
System.out.println("");
}
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (i == 0 && j == 0) {
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (i > 0 && j == 0){
feldb[i][j] = ' ';
System.out.print(feldb[i][j] + " |");
}
if (c > f) {
c = 'A';
}
if(c <= f && j > 0){
feldb[i][j] = c;
System.out.print(feldb[i][j] + " |");
c++;
}
if (j == 10){
System.out.println("");
}
}
}
}
}
You don't actually need array to print the maze , nested loops is enough for that. 2d Array is only required to store the input. Please try the below code:
int size = 10;
int [][] maze = new int[size][size];
while (true){
System.out.print(' ');
for (int i = 0; i < size; i++) {
System.out.print('|');
System.out.print((char) ('A' + i));
}
for (int i = 0; i < size; i++) {
System.out.println("");
System.out.print(i);
for (int j = 0; j < size; j++) {
System.out.print('|');
if(maze[i][j] > 0) {
System.out.print(maze[i][j]);
} else {
System.out.print(' ');
}
}
}
int row = -1;
int col = -1;
System.out.println("\nEnter CoOrdinates");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if(input.length() == 2) {
char charAt = input.charAt(0);
if(charAt >= 'A' && charAt <= 'A'+size-1) {
col = charAt-'A';
}
charAt = input.charAt(1);
if(charAt >= '0' && charAt <= '0'+size-1) {
row = charAt-'0';
}
if(row != -1 && col != -1) {
System.out.println("Enter Action");
input = scanner.nextLine();
int action = Integer.parseInt(input);
maze[row][col] = action;
} else {
System.out.println("Incorrect Input");
}
}
}

Print pyramid of * in Java

I'm wondering if you could help me out. I'm trying to write a nested for loop in java that displays a number pyramid triangle that looks like
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
This is what I have so far:
class Triagle {
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String[] args) {
printTriagle(12);//I want to set the triangle to be height of 12
}
}
My result is not equal to the expected output:
___________*#
__________*_*#
_________*_*_*#
________*_*_*_*#
_______*_*_*_*_*#
______*_*_*_*_*_*#
_____*_*_*_*_*_*_*#
____*_*_*_*_*_*_*_*#
___*_*_*_*_*_*_*_*_*#
__*_*_*_*_*_*_*_*_*_*#
_*_*_*_*_*_*_*_*_*_*_*#
*_*_*_*_*_*_*_*_*_*_*_*#
I have updated your code and added comments so that you can understand. Refer to the code below:
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print("_");
}
String s = "_";
if (i + 1 >= n) // check if it is the last line
s = "*"; // change to print * instead of _
for (int j = 0; j <= i; j++) {
// printing stars
if (j == i)
System.out.print("*#"); // check if the last print of the line
else if (j == 0)
System.out.print("*" + s); // check if the first print of the line
else
System.out.print(s + s);
}
System.out.println();
}
}
Result:
___________*#
__________*_*#
_________*___*#
________*_____*#
_______*_______*#
______*_________*#
_____*___________*#
____*_____________*#
___*_______________*#
__*_________________*#
_*___________________*#
***********************#
Try this
public static void printTriagle(int n) {
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
// printing stars
if(i == (n-1)){
System.out.print("**");
}
else{
System.out.print((j == 0 || j == i) ? "* " : " ");
}
}
System.out.println();
}
}
Your issue is here:
for (int j=0; j<=i; j++){
// printing stars
System.out.print("* ");
}
Here, it prints a star for each number between 0 and i, but it only should print a star if it is exactly 0 or i.
Try something like this:
for (int j=0; j<=i; j++){
if ( i == n ) {
System.out.print("* ");
} else {
System.out.print(j == 0 || j == i ? "* " : " ");
}
}
EDIT: You may still have to adapt your code to get the bottom line printed correctly, in case that line has to be all stars
This is what you need to do:
public static void printTriagle(int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < 2*n; j++) {
if(i == n-1) {
System.out.print((j != 2*n-1) ? "*" : "#");
}
else {
if(i+j == n-1) {
if(i == 0) {
System.out.print("*#");
break;
}
else {
System.out.print("*");
}
}
else if(j-i == n-1) {
System.out.print("*#"); break;
}
else {
System.out.print("_");
}
}
}
System.out.println();
}

Java printing patterns using for loops

I need to get the following pattern
have developed following code.
public static void main(String[] args) {
int number = 9;
for(int i=0;i<9;i++){
for(int j=0;j<18;j++){
if(number==6)
continue;
System.out.print(number);
}
if(number != 6)
System.out.println();
number--;
}
}
But I cant think about the logic to get the curved part of the pattern. Can Anyone give an opinion?
if (j < number || j >= 18 - number)
System.out.print(number);
else
System.out.print(" ");
You could try this:
public class CurveOutput {
public static void main(String args[]) {
int startNumber = 9;
for (int currentNum = startNumber; currentNum >= 0; currentNum--) {
StringBuilder line = new StringBuilder();
for (int i = 0; i < currentNum; i++) {
line.append(currentNum);
}
for (int i = 0; i < startNumber - currentNum; i++) {
line.append(" ");
}
System.out.println(line.toString() + line.reverse().toString());
}
}
}
this snippet produce:
999999999999999999
88888888 88888888
7777777 7777777
666666 666666
55555 55555
4444 4444
333 333
22 22
1 1
From my perspective it is really about programming on a correct level of abstraction.
The requirement is not to put as many spaces in the start or at the end, but rather to align the numbers to left or right. If there would be such functionality, it would be better and most likely more readable. And there is such:
public static void main(String args[]) {
int startNumber = 9;
for (int i = startNumber; i > 0; i--) {
String numberToPrint = Strings.repeat("" + i, i); // from Google Guava
String leftHalf = String.format("%-" + startNumber + "s", numberToPrint);
String rightHalf = String.format("%" + startNumber + "s", numberToPrint);
System.out.printf("%s%s%n", leftHalf, rightHalf);
}
}
Try this...
int num=9,save=9;
for(int i=1;i<10;i++)
{
for(int j=1;j<=18&&num!=6;j++)
{
int t=save-num;
if(((j<=(9-t)) || (j>(9+t))))
System.out.print(num);
else
System.out.print(" ");
}
num=num-1;
System.out.println("\n");
}
package q17;
public class Q17 {
public static void main(String[] args) {
int x = 9, y = 10;
for (int i = x; i >= 1; i--) {
if (i == 6) {
x--;
y++;
continue;
}
for (int j = 1; j <= 18; j++) {
if ((i != 9) && ((j >= x) && (j <= y))) {
System.out.print(" ");
} else {
System.out.print(i);
}
}
if (i != 9) {
x--;
y++;
}
System.out.println();
}
}
}

How can I turn the null character into a blank character in my Java TicTacToe program?

At the moment, I have working code for a simple Tic Tac Toe program written in java. The only problem, as you'll see below, is that the null character (\u0000) is being printed instead of an open space when my board is displayed.
My professor told us to write this program in such a way that null spaces are detected and to fill them with either X or O, which I did.
Now, I would like to be able to change the null character from appearing as 00 to just a blank space since the format is incorrect otherwise.
I already tried simply erasing the '\u0000' character and replacing it with a ' ' character but then my board doesn't show up at all. Any help is appreciated!
import java.util.Scanner;
public class TicTacToe
{
public static void main(String[] args)
{
char[][] board = new char[3][3];
while (true) {
makeCompMove(board, 'X');
displayBoard(board);
if(isWon('X', board)) {
System.out.println("\n\nComputer won!");
System.exit(1);
}
else if (isDraw(board)) {
System.out.println("\n\nDraw Game! No winner");
System.exit(2);
}
makeAMove(board, 'O');
displayBoard(board);
if (isWon('O', board)) {
System.out.println("\n\nPlayer won!");
System.exit(3);
}
else if (isDraw(board)) {
System.out.println("\n\nDraw Game! No winner");
System.exit(4);
}
}
}
public static void displayBoard(char[][] board)
{
for(int k = 0; k < 3; k++)
{
for(int i = 0; i < 28; i++)
{
System.out.print("-");
}
System.out.println();
for(int j = 0; j < 3; j++)
{
System.out.print("|" + " " + board[k][j] + " ");
}
System.out.println("|");
}
for(int i = 0; i < 28; i++)
{
System.out.print("-");
}
}
public static void makeAMove(char[][] board, char o)
{
Scanner input = new Scanner(System.in);
while(true)
{
System.out.print("\n\nYour turn. Enter a row and col(0,1 or 2): ");
int row = input.nextInt();
int col = input.nextInt();
if(row > 2 || row < 0 || col > 2 || col < 0)
{
System.out.println("Incorrect Input. Try Again!");
continue;
}
if(board[row][col] == '\u0000')
{
System.out.print("\n You (O) have made your move...\n\n");
board[row][col] = 'O';
break;
}
else
System.out.println("Incorrect Input. Try Again!");
}
}
public static void makeCompMove(char[][] board, char x)
{
System.out.println();
System.out.println();
System.out.print("Computer (X) has made his move...\n");
while(true)
{
int row = (int)(Math.random()*3);
int col = (int)(Math.random()*3);
if(board[row][col] == '\u0000')
{
board[row][col] = x;
break;
}
}
System.out.println();
}
public static boolean isDraw(char[][] board)
{
for(int row = 0; row < 3; row++)
{
for(int col = 0; col < 3; col++)
{
if(board[row][col] == '\u0000')
{
return false;
}
}
}
return true;
}
public static boolean isWon(char x, char[][] board)
{
// Check Rows
for (int i = 0; i < 3; i++)
if (x == board[i][0] && x == board[i][1] && x == board[i][2])
return true;
// Check Columns
for (int j = 0; j < 3; j++)
if (x == board[0][j] && x == board[1][j] && x == board[2][j])
return true;
// Check first diagonal
if (x == board[0][0] && x == board[1][1] && x == board[2][2])
return true;
// Check second diagonal
if (x == board[0][2] && x == board[1][1] && x == board[2][0])
return true;
return false;
}
}
No need to change any of code You Just Check before display
in displayBoard use like this
for(int j = 0; j < 3; j++)
{
if(board[k][j]=='\u0000')
System.out.print("|" + " ");
else
System.out.print("|" + " " + board[k][j] + " ");
}
The elements in the two-dimensional array are set to the null character when the array is initialized. If you want to convert them all to a space, then iterate over them all and replace the character with a space.
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = ' ';
}
}
If the place is never used, then it will have a space instead of the null character in it. Do this before you use the array.

Categories

Resources