Creating a chess board with system.out.println() in java - java

I am trying to create a chessboard that looks like this:
---------------------------------
| | | | | | | | |
---------------------------------
| | | | | | | | |
---------------------------------
| | | | | | | | |
---------------------------------
| | | | | | | | |
---------------------------------
| | | | | | | | |
---------------------------------
| | | | | | | | |
---------------------------------
| | | | | | | | |
---------------------------------
| | | | | | | | |
---------------------------------
For some reason I cant get the last line on each row to appear where it suppose to.
Here is my code
public static final int BOARD_SIZE = 8;
public void displayChessBoard(){
for (int row = 0; row < BOARD_SIZE; row++)
{
System.out.println("");
System.out.println("---------------------------------");
for (int column = 0; column < BOARD_SIZE; column++)
{
System.out.print("| " + " " + " ");
}
}
System.out.println("");
System.out.println("---------------------------------");
}
main just calls the method displayChessBoard().
Here is my output
---------------------------------
| | | | | | | |
---------------------------------
| | | | | | | |
---------------------------------
| | | | | | | |
---------------------------------
| | | | | | | |
---------------------------------
| | | | | | | |
---------------------------------
| | | | | | | |
---------------------------------
| | | | | | | |
---------------------------------
| | | | | | | |
---------------------------------

Add another print after the inner for. Like this:
for (int row = 0; row < BOARD_SIZE; row++)
{
System.out.println("");
System.out.println("---------------------------------");
for (int column = 0; column < BOARD_SIZE; column++)
{
System.out.print("| " + " " + " ");
}
System.out.print("|");
}
System.out.println("");
System.out.println("---------------------------------");
Hope it helps...

You are printing 7 pipes, inner for cycle is going from 0 to 7 (column < BOARD_SIZE), just add a pipe print after inner cycle's end.
If you don't mind extra spaces at the end of each line just change for condition to column <= BOARD_SIZE.

You should change the BOARD_SIZE in second for-statement to 9:
This code generates the chess board just like you want:
public static void main(String args[])
{
for (int row = 0; row < 8; row++)
{
System.out.println("");
System.out.println("---------------------------------");
for (int column = 0; column < 9; column++)
{
System.out.print("| " + " " + " ");
}
}
System.out.println("");
System.out.println("---------------------------------");
}

Related

How to print only a static number of integers from a string

My program produces an ascii calendar with some events that are stored in an array. I need a way so that in the blank space of the calendar instead it prints the width of the calendar - 1 characters per line. How would I make it so that it only prints (lets say width = 5) the first 4 character, then the next 4.
Note: the program uses a for loop to make each line so it must be one statement that is repeated to print all of the characters in the string.
Example of desired outcome:
======================================================================
| | 1| 2| 3| 4| 5| 6|
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
======================================================================
| 7| 8| 9| 10| 11| 12| 13|
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
======================================================================
| 14| 15| 16| 17| 18| 19| 20|
| |St. Patri| | | | | |
| |ks day | | | | | |
| | | | | | | |
| | | | | | | |
======================================================================
| 21| 22| 23| 24| 25| 26| 27|
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
======================================================================
| 28| | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
======================================================================
Code so far:
public static void drawRow(int row) {
int dayofweek = startingDayOfWeek(month);
int daysinmonth = daysInMonth(month);
int dayspassed = 1;
for(int i = 0; i < row; i++) {
System.out.print("|");
for(int a = 1; a <= 7; a++) {
int length=String.valueOf(10).length();
for(int j = 1; j < Width - length; j++) {
System.out.print(" ");
}
if(dayofweek > 0) {
System.out.print(" ");
dayofweek--;
}
else {
if(dayspassed < 10) {
System.out.print(" ");
}
if(daysinmonth > 0) {
System.out.print(dayspassed);
daysinmonth--;
dayspassed++;
}
else {
System.out.print(" ");
}
}
System.out.print("|");
}
for(int t = 1; t < (Width /2); t++) {
System.out.println();
System.out.print("|");
for(int h = 1; h<=7; h++) {
for(int f = 1; f <= Width - 1; f++) {
eventChecker(month,day);
if(eventCheck == true) {
// part where I need it to either print an event if
// there is one, or line wrap the event.
System.out.print(" ");
}
System.out.print("|");
}
}
System.out.println();
for(int e = 1; e <= Width * 7; e++) {
System.out.print("=");
}
System.out.println();
}
dayspassed = 1;
daysinmonth = daysInMonth(month);
dayofweek = startingDayOfWeek(month);
I've marked the part I need to modify with a comment.
something like this will return the correct character for each cell:
private static char getEventChar(String event, int row, int column, int width) {
// we are interested in the n-th character in this String
int n = row * width + column;
if (n >= event.length()) {
return ' '; // if we passed the end of the name return space-character
}
return event.charAt(n);
}

I typed something meant for the console into my code, and I can't find where I messed up [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I was working on my assignment testing out to make sure it all worked, I accidentally typed an input meant for the console into my code and the output is no longer correct. Here is the code:
import java.util.*;
public class JTCalendar {
//This defines how big the calendar is
public static final int Width = 5;
public static void drawMonth(int month,int day) {
//Ascii art of a robot man
System.out.println(" /\\ /\\");
System.out.println(" / \\ / \\");
System.out.println(" ---------------");
System.out.println("(| (o) (o) |)");
System.out.println(" | wwww |");
System.out.println(" ----------------");
//This finds the center
for(int i = 1; i <= 1; i++) {
for(int j = 1; j <= (Width * 7) / 2; j++) {
System.out.print(" ");
}
System.out.print(month);
for(int d = 1; d <= (Width * 7) / 2 ; d++) {
System.out.print(" ");
}
System.out.println();
I believe the error got put somewhere along this area as this is the area that has a messed up output
}
//Size calculator
for(int g =1; g <= Width * 7; g++) {
System.out.print("=");
}
System.out.println();
drawRow(5);
displayDate(month,day);
}
//Start of the rows
public static void drawRow(int row) {
int day = 1;
for(int i = 0; i < row; i++) {
System.out.print("|");
for(int a = 1; a <= 7; a++) {
int length=String.valueOf(day).length();
for(int j = 1; j < Width - length; j++) {
System.out.print(" ");
}
System.out.print(day);
day++;
System.out.print("|");
}
System.out.println();
for(int t = 1; t < (Width /2); t++) {
System.out.print("|");
for(int h = 1; h<=7; h++) {
for(int f = 1; f <= Width - 1; f++) {
System.out.print(" ");
}
System.out.print("|");
}
}
for(int e = 1; e <= Width * 7; e++) {
System.out.print("=");
}
System.out.println();
}
//End of the rows
}
//Below displays the date
public static void displayDate(int month, int day) {
System.out.println("Month: " + month + "\nDay: " + day);
}
//End display
//Below seperates month and day into two ints
public static int monthFromDate(String date) {
String tokens[] = date.split("/");
return Integer.parseInt(tokens[0]);
}
I'm confident anything below this is proper but I'm still including it
public static int dayFromDate(String date) {
String tokens[] = date.split("/");
return Integer.parseInt(tokens[1]);
}
//End seperation of month and day
public static void main(String[] args) {
//Main scanner console
Scanner console = new Scanner(System.in);
System.out.print("What date would you like to look at? (mm/dd): ");
String date = console.next();
int day = dayFromDate(date);
int month = monthFromDate(date);
drawMonth(month, day);
//This draws the ascii calendar
Calendar cal = Calendar.getInstance();
day = cal.get(Calendar.DATE);
month = cal.get(Calendar.MONTH) + 1;
System.out.println("\nToday is: " + month + "/" + day + "\n");
drawMonth(month,day);
//This draws the calandar for the current date
}
}
Bad output:
/\ /\
/ \ / \
---------------
(| (o) (o) |)
| wwww |
----------------
2
===================================
| 1| 2| 3| 4| 5| 6| 7|
| | | | | | | |===================================
| 8| 9| 10| 11| 12| 13| 14|
| | | | | | | |===================================
| 15| 16| 17| 18| 19| 20| 21|
| | | | | | | |===================================
| 22| 23| 24| 25| 26| 27| 28|
| | | | | | | |===================================
| 29| 30| 31| 32| 33| 34| 35|
| | | | | | | |===================================
Month: 2
Day: 25
Today is: 2/13
/\ /\
/ \ / \
---------------
(| (o) (o) |)
| wwww |
----------------
2
===================================
| 1| 2| 3| 4| 5| 6| 7|
| | | | | | | |===================================
| 8| 9| 10| 11| 12| 13| 14|
| | | | | | | |===================================
| 15| 16| 17| 18| 19| 20| 21|
| | | | | | | |===================================
| 22| 23| 24| 25| 26| 27| 28|
| | | | | | | |===================================
| 29| 30| 31| 32| 33| 34| 35|
| | | | | | | |===================================
Month: 2
Day: 13
Good output:
/\ /\
/ \ / \
---------------
(| (o) (o) |)
| wwww |
----------------
2
===================================
| 1| 2| 3| 4| 5| 6| 7|
| | | | | | | |
===================================
| 8| 9| 10| 11| 12| 13| 14|
| | | | | | | |
===================================
| 15| 16| 17| 18| 19| 20| 21|
| | | | | | | |
===================================
| 22| 23| 24| 25| 26| 27| 28|
| | | | | | | |
===================================
| 29| 30| 31| 32| 33| 34| 35|
| | | | | | | |
===================================
Month: 2
Day: 25
Today is: 2/13
/\ /\
/ \ / \
---------------
(| (o) (o) |)
| wwww |
----------------
2
===================================
| 1| 2| 3| 4| 5| 6| 7|
| | | | | | | |
===================================
| 8| 9| 10| 11| 12| 13| 14|
| | | | | | | |
===================================
| 15| 16| 17| 18| 19| 20| 21|
| | | | | | | |
===================================
| 22| 23| 24| 25| 26| 27| 28|
| | | | | | | |
===================================
| 29| 30| 31| 32| 33| 34| 35|
| | | | | | | |
===================================
Month: 2
Day: 13
You need to add a System.out.println(); after drawing each row:
System.out.println();
for(int t = 1; t < (Width /2); t++) {
System.out.print("|");
for(int h = 1; h<=7; h++) {
for(int f = 1; f <= Width - 1; f++) {
System.out.print(" ");
}
System.out.print("|");
}
}
System.out.println(); // <== ADDED PRINTLN HERE
for(int e = 1; e <= Width * 7; e++) {
System.out.print("=");
}
System.out.println()
The problem is in the drawRow(int row) method , after you print out the '|' character using the for loop then it's not starting in a new line to print out the '=' characters ,you have to insert one System.out.println() statment to make it start in next line
your Code
for(int t = 1; t < (Width /2); t++) {
System.out.print("|");
for(int h = 1; h<=7; h++) {
for(int f = 1; f <= Width - 1; f++) {
System.out.print(" ");
}
System.out.print("|");
}
}
Newer Code
for(int t = 1; t < (Width /2); t++) {
System.out.print("|");
for(int h = 1; h<=7; h++) {
for(int f = 1; f <= Width - 1; f++) {
System.out.print(" ");
}
System.out.print("|");
}
System.out.println(""); //<------------ the only change you need to make
}

How to duplicated Excel rows?

This is my Excel data:
| | Animal | Step | IsGood |
|:-:|:------:|:----:|:------:|
| 1 | Dog | 1 | true |
| 2 | Cat | 2 | true |
I wish to duplicate all the rows in my Excel file (not including the Header row) and manipulate the data. My New Excel File should look like this:
| | Animal | Step | IsGood |
|:-:|:------:|:----:|:------:|
| 1 | Dog | 1 | true |
| 2 | Dog | 2 | false |
| 3 | Cat | 3 | true |
| 4 | Cat | 4 | false |
How do I this using Java? I'm using org.apache.poi library.
I am using this method to duplicate
private void duplicateInPlace() {
XSSFSheet firstSheetObj = this.firstWB.getSheet(firstSheetName);
XSSFSheet targetSheetObj = this.targetWB.createSheet(this.targetSheetName);
int firstSheetLen = firstSheetObj.getLastRowNum();
replaceMinusOnes(firstSheetObj,firstSheetObj);
int targetCursorPosition=0;
//
for (int i = 0; i < rangeStart ; i++) {
XSSFRow firstRow = firstSheetObj.getRow(i);
XSSFRow targetRow = targetSheetObj.createRow(targetCursorPosition);
this.copyRow(firstRow,targetRow);
targetCursorPosition+=1;
}//endfor
for (int i = rangeStart; i < rangeEnd ; i++) {
XSSFRow firstRow = firstSheetObj.getRow(i);
XSSFRow targetRow = targetSheetObj.createRow(targetCursorPosition);
this.copyRow(firstRow,targetRow);
XSSFRow targetRow2 = targetSheetObj.createRow(targetCursorPosition+1);
this.copyRow(firstRow,targetRow2); //this part duplicates
targetCursorPosition+=2;
}
for (int i = rangeEnd; i < firstSheetLen ; i++) {
XSSFRow firstRow = firstSheetObj.getRow(i);
XSSFRow targetRow = targetSheetObj.createRow(targetCursorPosition);
this.copyRow(firstRow,targetRow);
targetCursorPosition+=1;
}
}

how to print this horizontally?

Hey guys if you run this code with the given input you will get a vertical ruler
i'm trying to get a horizontal ruler using the given recursive functions any idea how to get there or hints ???
public class Ruler {
// draw a tick with no label
public static void drawOneTick(int tickLength) {
drawOneTick(tickLength, -1);
}
// draw one tick
public static void drawOneTick(int tickLength, int tickLabel) {
for (int i = 0; i < tickLength; i++)
System.out.print("-");
if (tickLabel >= 0)
System.out.print(" " + tickLabel);
System.out.print("\n");
}
public static void drawTicks(int tickLength) {
if (tickLength > 0) {
drawTicks(tickLength-1);
drawOneTick(tickLength);
drawTicks(tickLength-1);
}
}
public static void drawRuler(int nInches, int majorLength) {
drawOneTick(majorLength, 0);
for (int i = 1; i <= nInches; i++) {
drawTicks(majorLength-1);
drawOneTick(majorLength, i);
}
}
public static void main(String[] args) {
drawRuler(3,4);
}
}
Assuming u want to do Ruler like this:
0 1 2 3 4 5
| | | | | |
| | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
It will be hard to it via recursive methods, because you've limited with print/println(), and because text is 1D ^^
So you wont be able to draw whole "tickline" in 1 method, no, tickline with height N will take N+1 printlines.
But, as you see, i've achieved this ruler, only with loops:
SPOLER!
package com.company;
public class Main {
private static String drawLabels(int count, int offset) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= count; i++) {
sb.append(i);
for (int spaces = 0; spaces < offset; ++spaces) {
sb.append(' ');
}
}
return sb.toString();
}
private static String drawTicks(int count, int offset) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= count; i++) {
sb.append('|');
for (int spaces = 0; spaces < offset; ++spaces) {
sb.append(' ');
}
}
return sb.toString();
}
public static void drawRuler(int nInches, int majorLength) {
// labels part
int offset = (int) Math.pow(2, majorLength - 1) - 1;
System.out.println(drawLabels(nInches, offset));
// rest
for (int line = majorLength; line > 0; --line) {
int ticksOffset = (int) Math.pow(2, line - 1) - 1;
int ticksNumber = nInches * (int) Math.pow(2, majorLength - line);
System.out.println(drawTicks(ticksNumber, ticksOffset));
}
}
public static void main(String[] args) {
drawRuler(5,5);
}
}
Here is a solution more inline with your example. You can still do it with recursion without having to use the power function to calculate the position of the tick.
I suggest to start with a smaller problem: How to draw the minor ticks between the major ticks. We can use the recursion for this one. We also have to realize that we can not anymore print the entire tick at once (as Fen1kz correctly mentioned) because it spans across multiple lines. We will have to loop over the number of lines and in the tick function either draw a tick or an empty space based on which line we are drawing. Once we have this we can easily draw one set of minor ticks. After that it is not too hard to add the rest of the code to repeat the previous and add the major ticks.
For completeness here is the whole code:
public class Ruler {
private static void drawMinorTicks(int line, int ticks) {
if (ticks > 1) {
drawMinorTicks(line, ticks - 1);
}
if (line <= ticks) {
System.out.print('|');
} else {
System.out.print(' ');
}
if (ticks > 1) {
drawMinorTicks(line, ticks - 1);
}
}
private static void drawSingleMajorTick(int line, int ticks, int label) {
if (line <= ticks) {
System.out.print('|');
} else {
System.out.print(label);
}
}
private static void drawMajorTicks(int inches, int line, int ticks) {
drawSingleMajorTick(line, ticks, 0);
for (int i = 1; i <= inches; i++) {
drawMinorTicks(line, ticks - 1);
drawSingleMajorTick(line, ticks, i);
}
}
private static void drawRuler(int inches, int ticks) {
for (int i = 1; i <= ticks + 1; ++i) {
drawMajorTicks(inches, i, ticks);
System.out.println();
}
}
public static void main(String[] args) {
drawRuler(5, 5);
}
}
And the output is:
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | |
| | | | | |
0 1 2 3 4 5

Java formatted output issue

public static void main(String[] args) {
Formatter fmt = new Formatter();
String russianAlphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
String text = "c точки зрения банальной эрудиции, каждый индивидуум вышедший из сферы эмбрионального развития" +
"не способен патологически идеализировать метаморфические абстракции";
//printing text String
for(int i = 0; i < text.length(); i++){
fmt.format("%c ",text.charAt(i));
System.out.print(fmt);
}
System.out.println();
//searching a position index in alphabet
for(int i = 0; i < text.length(); i++){
fmt.format("%02d ",russianAlphabet.indexOf(text.charAt(i)));
System.out.print(fmt);
}
}
I just need nice compact output of two strokes, one under the other. First shows chars split-ted by space, second shows position of char in alphabet. What is wrong with format output? It returns a lot of random text. (Very sorry for bad English).
Save your program file as UTF-8. Try this code below.
I don't think you were printing the right thing here.
System.out.print(fmt);
Also note that in your program you typed some of your chars
as latin not as cyrillic (the first c for example was latin).
public class Test33 {
public static void main(String[] args) {
String russianAlphabet = " абвгдеёжзийклмнопрстуфхцчшщъыьэюя";
String text = "с точки зрения банальной эрудиции, каждый индивидуум вышедший из сферы эмбрионального развития " +
"не способен патологически идеализировать метаморфические абстракции";
for(int i = 0; i < text.length(); i++){
System.out.print(String.format("%3c | ",text.charAt(i)));
}
System.out.println();
for(int i = 0; i < text.length(); i++){
System.out.print(String.format("%3d | ",russianAlphabet.indexOf(text.charAt(i))));
}
System.out.println();
}
}
OUTPUT:
с | | т | о | ч | к | и | | з | р | е | н | и | я | | б | а | н | а | л | ь | н | о | й | | э | р | у | д | и | ц | и | и | , | | к | а | ж | д | ы | й | | и | н | д | и | в | и | д | у | у | м | | в | ы | ш | е | д | ш | и | й | | и | з | | с | ф | е | р | ы | | э | м | б | р | и | о | н | а | л | ь | н | о | г | о | | р | а | з | в | и | т | и | я | | н | е | | с | п | о | с | о | б | е | н | | п | а | т | о | л | о | г | и | ч | е | с | к | и | | и | д | е | а | л | и | з | и | р | о | в | а | т | ь | | м | е | т | а | м | о | р | ф | и | ч | е | с | к | и | е | | а | б | с | т | р | а | к | ц | и | и |
19 | 0 | 20 | 16 | 25 | 12 | 10 | 0 | 9 | 18 | 6 | 15 | 10 | 33 | 0 | 2 | 1 | 15 | 1 | 13 | 30 | 15 | 16 | 11 | 0 | 31 | 18 | 21 | 5 | 10 | 24 | 10 | 10 | -1 | 0 | 12 | 1 | 8 | 5 | 29 | 11 | 0 | 10 | 15 | 5 | 10 | 3 | 10 | 5 | 21 | 21 | 14 | 0 | 3 | 29 | 26 | 6 | 5 | 26 | 10 | 11 | 0 | 10 | 9 | 0 | 19 | 22 | 6 | 18 | 29 | 0 | 31 | 14 | 2 | 18 | 10 | 16 | 15 | 1 | 13 | 30 | 15 | 16 | 4 | 16 | 0 | 18 | 1 | 9 | 3 | 10 | 20 | 10 | 33 | 0 | 15 | 6 | 0 | 19 | 17 | 16 | 19 | 16 | 2 | 6 | 15 | 0 | 17 | 1 | 20 | 16 | 13 | 16 | 4 | 10 | 25 | 6 | 19 | 12 | 10 | 0 | 10 | 5 | 6 | 1 | 13 | 10 | 9 | 10 | 18 | 16 | 3 | 1 | 20 | 30 | 0 | 14 | 6 | 20 | 1 | 14 | 16 | 18 | 22 | 10 | 25 | 6 | 19 | 12 | 10 | 6 | 0 | 1 | 2 | 19 | 20 | 18 | 1 | 12 | 24 | 10 | 10 |

Categories

Resources