Reputation: 25
I am new to java and taking an intro course.
I have been able to figure out the majority of my question however i am stuck on the last step.
The end result is supposed to be this using four or less system.out.print or system.out.println statements:
*******
* *****
* ****
* ***
* **
* *
*******
and I have created this
*******
* *****
* ****
* ***
* **
* *
*
This is my code. Is there anything you guys can see that could help?
public class StarPatterns {
public static void main(String[] args) {
int col;
int row;
for (row = 6; row >= 0 ; row--) {
if (row >= 0)
System.out.print("*");
for (col = row; col < 6; col++) {
System.out.print(" ");
}
for (col = row; col > 0; col--) {
System.out.print("*");
}
System.out.println();
}
}
}
Upvotes: 1
Views: 2425
Reputation: 148880
EDIT: was missing by one : fixed
What do you think of that :
public static void main(String[] args) {
for (int row=0; row<7; row++) {
for (int col=0; col<7; col++) {
System.out.print((col == 0) || (row == 6) || (col > row) ? "*" : " ");
}
System.out.println();
}
}
Result is :
*******
* *****
* ****
* ***
* **
* *
*******
Upvotes: 1
Reputation: 15399
You can do it in 1 without ternary operators since I assume you haven't learned it yet (or at least your instructor wouldn't like you using them):
public class StarPatterns {
public static void main(String[] args) {
int col;
int row;
for (row = 0; row < 7; row++) {
for (col = 0; col < 7; col++) {
String symbol = " ";
if (row == 0 || col == 0 || col > row || row == 6) {
symbol = "*";
}
if (col == 6) {
symbol += System.getProperty("line.separator");
}
System.out.print(symbol);
}
}
}
}
Output:
*******
* *****
* ****
* ***
* **
* *
*******
Upvotes: 0
Reputation: 450
public class stars {
public static void main(String[] args) {
int row = 7;
int col = 7;
int count;
for (int i=0;i<row;i++)
{
count = i;
System.out.print("*");
for (int c=1;c<col;c++)
{
if (count == 0 || count == row-1)
{
System.out.print("*");
}
else
{
System.out.print(" ");
count--;
}
}
System.out.println("");
}
}
4 System.out prints:
Update:
3 System.out prints:
public static void main(String[] args) {
int row = 7;
int col = 7;
int count;
for (int i=0;i<row;i++)
{
count = i;
//System.out.print("*");
for (int c=0;c<col;c++)
{
if (count == 0 || count == row-1 || c == 0)
{
System.out.print("*");
}
else
{
System.out.print(" ");
count--;
}
}
System.out.println("");
}
}
Probably not optimal (memory usage) but maybe good for logic:
Using 2 System.out prints:
public static void main(String[] args) {
int row = 7;
int col = 7;
int count;
String strNewLine = "*" + System.lineSeparator();
String str = "*";
String strToPrint;
for (int i=0;i<row;i++)
{
count = i;
for (int c=0;c<col;c++)
{
if (count == 0 || count == row-1 || c == 0)
{
if (c == row-1)
{
strToPrint = strNewLine;
}
else
{
strToPrint = str;
}
System.out.print(strToPrint);
}
else
{
System.out.print(" ");
count--;
}
}
}
}
Upvotes: 2