Trying to draw a square with letters in it, but a for loop is causing problems.
I have a class that draws an arena and adds drones(letters) to it, the drones are saved in an array an get displayed by every time their coordinate is reached.
for e.g (The main function is below).
The drone array is in the drones 2d array, the function that displays them is in the showIt function which gets called in the vertical function. The problem is that when I have one drone it gets drone perfectly, but when I add more than one drone, the width of the arena gets doubled, tripled, etc.
public class DroneArena {
char myDrone = 'X';
boolean positionReached = false;
int[][] drones = {{12, 17}, {2, 10}, {5, 14}};
public DroneArena(int w, int h, char border) {
horizental(w, border);
for(int i = 0; i < h; i ) {
vertical(w, i, border);
}
horizental(w, border);
}
void showIt(int h, int i, char drone) {
if(drones.length > 0) {
for(int j = 0; j < 3; j ) {
if((h == drones[j][0]) && (i == drones[j][1])) {
System.out.print(drone);
}else {
System.out.print(" ");
}
}
}else {
System.out.print(" ");
}
}
void vertical(int w,int h, char border) {
System.out.print(border);
for(int i = 0; i < w - 2; i ) {
// System.out.print(" ");
showIt(h, i , 'D');
}
System.out.println(border);
}
void horizental(int w, char border) {
for(int i = 0; i < w -1; i ) {
System.out.print(border);
}
System.out.println(border);
}
}
//main method
public class Main {
public static void main(String[] args) {
DroneArena arena = new DroneArena(20, 20, '-');
}
}
CodePudding user response:
You should print char drone
when you find one drone. Only one space should be printed if not found.
void showIt(int h, int i, char drone) {
for (int j = 0; j < drones.length; j ) {
if ((h == drones[j][0]) && (i == drones[j][1])) {
System.out.print(drone);
return;
}
}
System.out.print(" ");
}
output:
--------------------
- -
- -
- D -
- -
- -
- D -
- -
- -
- -
- -
- -
- -
- D-
- -
- -
- -
- -
- -
- -
- -
--------------------