I'm working on a gameboard that prints out something like this:
Here's the code I wrote
void showBoard() {
String city1, city2, city3, city4, city5, city6, city7, city8, city9, city10;
// I wrote like this because I want each box to have the size to hold 11 characters.
city1 = "Cario ";
city2 = "Phuket ";
city3 = "New delhi ";
city4 = "Hanoi ";
city5 = "Paris ";
city6 = "LA ";
city7 = "Sydney ";
city8 = "Tokyo ";
city9 = "Seoul ";
city10 = "START ";
char[][] cities = new char[10][];
for (int i = 0; i < 10; i++) {
cities[i] = new char[11];}
cities[0] = city1.toCharArray();
cities[1] = city2.toCharArray();
cities[2] = city3.toCharArray();
cities[3] = city4.toCharArray();
cities[4] = city5.toCharArray();
cities[5] = city6.toCharArray();
cities[6] = city7.toCharArray();
cities[7] = city8.toCharArray();
cities[8] = city9.toCharArray();
cities[9] = city10.toCharArray();
for (int i = 0; i < 11; i++)
System.out.print(cities[0][i]);
for(int k = 0; k < 2; k++) {
for (int q = 0; q < 5; q++) {
for(int i = 0; i < 13; i++) {
System.out.print("-");}}
System.out.println();
//There's the <Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10 > error because of the code from here....
for(int i = 0; i < 2 ; i++) {
for(int j = 0; j < 5; j++) {
for (int q = 0; q < cities.length; q++) {
if (q%11 == 0)
System.out.print("|");
else {
for (int p = 0; p < cities[q].length; p++ )
System.out.print(cities[p][q]);
}
}
System.out.print(" ");
}
System.out.println();}
//to here
for (int q = 0; q < 5; q++) {
for(int i = 0; i < 13; i++) {
System.out.print("-");}}
System.out.println();
if (k == 0) {
for(int i = 0; i < 65; i++) {
if (i == 0)
System.out.print("↑");
else if (i == 64)
System.out.println("↓");
else
System.out.print(" ");}}
}
System.out.println();
}
There are two problems that I really can't solve:
1.Shortening the code for cities[0~9] = city1~10.toCharArray();
2.Printing out the arrays like the image.
The couln't print nice seperate boxes, so I just made the boxes like they're inside fallen ladders
Here are the results from one of my test runs.
I wrote a method to give me the length of the city with the longest name. I tested this method.
Then, I wrote a method to create the dashed line. I tested this method.
Then I wrote a method to give me the line with 5 of the 10 city names. I tested this method several times. I fixed problems that cropped up in the previous methods.
Then I put all the methods together to create the output you see.
Write a little, test a lot. There's no way you can write an entire method like
showBoard
and expect it to work properly. Write a little, test a lot. And use methods to separate logical blocks of code.I couldn't be bothered to look up the arrow symbols. I leave that bit of code to you.
Here's the complete runnable code.