I need to create a box using user inputs. My inputs are the dimensions (height x width), the "interior" (the character that the box is filled with), and the "border" (the character surrounding the interior). I'm almost done, I believe; I can assemble the box given the dimensions and border, but I'm struggling to figure out how to fill the inside.
I don't know how to use decision statements to determine which characters belong on which line. If the current line is the first line, I want to print only border characters, or if the current character on the line is the first character in that line, print a border character, but print the interior for the following characters (until the end char), etc.
My code:
// Below this comment: import the Scanner
import java.util.Scanner;
public class Box {
public static void main(String[] args) {
// Below this comment: declare and instantiate a Scanner
Scanner scnr = new Scanner(System.in);
// Below this comment: declare any other variables you may need
int width;
int height;
char border;
char interior;
// Below this comment: collect the required inputs
System.out.println("Enter width : ");
width = scnr.nextInt();
System.out.println("Enter height : ");
height = scnr.nextInt();
System.out.println("Enter border : ");
border = scnr.next().charAt(0);
System.out.print("Enter interior : ");
interior = scnr.next().charAt(0);
// Below this comment: display the required results
for (int j = 0; j < height; j++) {
for (int i = 1; i < width; i++) {
System.out.print(border);
}
System.out.print(border);
System.out.println("");
}
}
}
As an arbitrary example, running my code with 7x5 dimensions and X and O characters gives me:
XXXXXXX
XXXXXXX
XXXXXXX
XXXXXXX
But my desired result would be:
XXXXXXX
XOOOOOX
XOOOOOX
XOOOOOX
XXXXXXX
Change:
for (int j = 0; j < height; j++) {
for (int i = 1; i < width; i++) {
System.out.print(border);
}
System.out.print(border);
System.out.println("");
}
To:
for (int j = 0; j < height; j++) {
for (int i = 1; i <= width; i++) {
if (j==0 || j==(height-1)) {
System.out.print(border);
}
else {
if (i==1 || i==width) {
System.out.print(border);
}
else {
System.out.print(interior);
}
}
}
System.out.println();
}
This could obviously be written in many different ways, some much more compact than this. I think this way is easy to understand, though...
For instance, here's a shorter version that works, but is harder to interpret:
for (int j = 0; j < height; j++) {
for (int i = 1; i <= width; i++) {
System.out.print(((j==0 || j==(height-1)) || (i==1 || i==width)) ? border : interior);
}
System.out.println();
}