Re: Removing the middle cell
Quote:
Originally Posted by
Shyamz1
Hi guys, i have created a program that outputs and prints a rectangle when given the width and height as command line arguments. I've got it to add 1 row and column if the number of rows or columns is even, so that the rectangle as a middle cell. I want to take this cell out (i.e. replace with spaces).
How would i get it to do this? Would i need to put in a loop or as an if statement.
Code java:
public class PrintHoledRectangle
{
public static void main(String [] args)
{
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
int count = width * height;
int middleCell = ((width*height)/2)+ 1;
if ((count % 2) == 0 && height == width)
{
width+=1;
height+=1;
}
else if ((count % 2) == 0 && (width % 2) == 0 && (height % 2) !=0)
width+=1;
else if ((count % 2) == 0 && (height % 2) == 0 && (width % 2) !=0)
height+=1;
else if ((count % 2) == 0 && (height % 2) == 0 && (width % 2) == 0)
{
height+=1;
width+=1;
}
for (int row = 1; row <= height; row++)
{
for (int column = 1; column <= width; column++)
System.out.print("[_]");
System.out.println();
} // for
for (int i = 1; i < middleCell; i++)
{
i = middleCell;
System.out.print(" ");
}
} // main
} // class PrintHoledRectangle
Kind Regards
Shyam
I also tried an if statement inside the loop:
Code java:
for (int i=0;i<middleCell;i++)
{
if i==middleCell
system.out.println(" ");
didnt work though :(
Hmmmm....if you want to take it out, would the width and height be 1 less then?
Do the width and height include spaces?
If not, you should be decrementing it by 1, not incrementing it.
You don't have a statement, probably an else would be best, to handle if count%2 !=0.
Also, what does your output look like so far?
Are you trying to make a grid of rectangles?
Also, your for loop:
Code java:
for (int row = 1; row <= height; row++)
{
for (int column = 1; column <= width; column++)
System.out.print("[_]");
System.out.println();
} // for
will only print one rectangle per line.
middle cell is an int. Are you trying to make it a rectangle?
Re: Removing the middle cell
Ahhhh....I think I'm starting to see what's going on.
The thing is, if you have an even number of rectangles, you're going to have 2 middle cells.
That's why you're adding one to the number of rows and/or columns, to make it so there's only 1 middle cell.
That will make it even again.
A better way would be to make a 2D array
Code java:
// first make sure that you've already added the extra cell
String[][] array = new String[rows][columns];
for (int rows = 0; rows < array.length; rows++)
{
for (int columns =0; columns < array[rows].length; columns++)
array[rows][columns] ="[_]";
}
// not sure if you need a second pair of brackets after second for statement. You'll have to check on that one.
Say for 5 rows and 5 columns
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
for a count of n * m where n and m are both odd, set the
((n*m)/2) + 1 element to " ";