Mac Quick Java Question (Basic)

MBP123

macrumors regular
Original poster
May 26, 2006
192
0
I need to have the program printout the attached image.

I already have the code for all of it but the diamond in the center as follows:
Code:
public class threes {
   public static void main( String[] args )
   {
	int rows, columns;
        for (rows=1; rows<=1; rows++)
	   {
		for (columns=1; columns<=36; columns++)
				{
					System.out.print("*");
				}
			System.out.print("\n");
			}
      
	
	for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("***");
			
			}
		System.out.print("   ");
	}
        
        System.out.print("\n");
        
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("***");
			
			}
		System.out.print("   ");
	}
        System.out.print("\n");
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("   ");
                        
			
			}
		System.out.print("***");
	}
        System.out.print("\n");
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("   ");
                        
			
			}
		System.out.print("***");
	}
        
	System.out.print("\n");
        
        for (rows=1; rows<=1; rows++)
	   {
		for (columns=1; columns<=36; columns++)
				{
					System.out.print("*");
				}
			System.out.print("\n");
			}
        System.out.print("\n");// END OF FIRST SECTION
       
        


            // DIAMOND SHAPE
        
        
        
         for (rows=1; rows<=1; rows++)// START OF SECOND SECTION
	   {
		for (columns=1; columns<=36; columns++)
				{
					System.out.print("*");
				}
			System.out.print("\n");
			}
      
       
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("   ");
                        
			
			}
		System.out.print("***");
	}
        
	
        System.out.print("\n");
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("   ");
                        
			
			}
		System.out.print("***");
	}
        
	System.out.print("\n"); 
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("***");
			
			}
		System.out.print("   ");
	}
        
        System.out.print("\n");
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("***");
			
			}
		System.out.print("   ");
	}
        
        System.out.print("\n");
         for (rows=1; rows<=1; rows++)
	   {
		for (columns=1; columns<=36; columns++)
				{
					System.out.print("*");
				}
			System.out.print("\n");
			}
        
	System.exit( 0 );   
   } // end main
} // end of program

The first question would be if there is any way to reduce and simplify that code, but using nothing more advanced than "for" loops.

Secondly, I am stuck on the diamond part. Using a for loop, I get stuck with the following code:

Code:
// third nested for loop ... what is the output here?
public class diamond {
   public static void main( String[] args )
   {
	int rows, columns;
	
	for (rows=1; rows<=3; rows++)
	{
		for (columns=1; columns < rows; columns++)
		{
			System.out.print(" ");
			}
		System.out.print("*\n");
	}			
	System.out.print("\n");
	System.exit( 0 );   
   } // end main
} // end of program
Any help is appreciated, and thanks in advance.
 

Attachments

MBP123

macrumors regular
Original poster
May 26, 2006
192
0
ive changed what i have so bar a bit

Code:
public class diamond {
   public static void main( String[] args )
   {
	int rows;
        
        
for(rows=1; rows<=9; rows++)
{

    if(rows%2 != 0)

            System.out.print ("\n *");

        
}
for(rows=9; rows>0; rows--)
{

    if(rows%2 != 0);

            System.out.print ("\n *");

        
}
            
   } // end main
} // end of program
getting there, but still a little stuck
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
First, you should get rid of all your redundant { } pairs. For example, in this loop:

Code:
for (i = 0 ; i < 6 ; i++ ) 
{ 
      System.out.print(" ") ; 
}
you don't need the braces. There is only one clause to execute under the FOR, so simplify and de-clutter your program.

To make your program smaller, you can create methods to call to do repetitive tasks. For instance, create a method to print out a line of stars, and then call it 4 times. Create a method to print out "***bbb" (where "b" is a blank) across a line and call it 4 times. Create a method to print out "bbb***" across a line and call it 4 times too.

For the diamond, I worked it out using a line equation in slope/intercept form (y = mx - b, where y works out to be the number of stars to print each line, and x is the iteration number). I ended up with very tight code. Use a piece of graph paper to work it out. I started out by observing the following characteristics:

1) there are 36 columns, and the the diamond starts in the middle.
2) for each line printed, the number of spaces decreases by one, until the middle one is printed, then the number of spaces increases by one.
3) The count of stars printed each line has a pattern:
1, 3, 5, 7, 9, 7, 5, 3, 1
4) If I wanted to write a FOR loop, I would need a contiguous range of numbers that would peak in the middle. I decided on a range of -4 to 4. That gives 9 iterations, and using the absolute value method, I could achieve a peak in the middle. This range also happens to coincide perfectly on graph paper (although on graph paper, the diamond is sideways).

My total progam is 59 lines, with a blank line and a comment line around most lines of code.

Todd

Code:
************************************
***   ***   ***   ***   ***   ***   
***   ***   ***   ***   ***   ***   
   ***   ***   ***   ***   ***   ***
   ***   ***   ***   ***   ***   ***
************************************
                *
               ***
              *****
             *******
            *********
             *******
              *****
               ***
                *
************************************
   ***   ***   ***   ***   ***   ***
   ***   ***   ***   ***   ***   ***
***   ***   ***   ***   ***   ***   
***   ***   ***   ***   ***   ***   
************************************
 

saltyzoo

macrumors 65816
Oct 4, 2007
1,065
0
First, you should get rid of all your redundant { } pairs. For example, in this loop:

Code:
for (i = 0 ; i < 6 ; i++ ) 
{ 
      System.out.print(" ") ; 
}
you don't need the braces. There is only one clause to execute under the FOR, so simplify and de-clutter your program.
Wow, I could not disagree more. Some of the most annoying and difficult to spot bugs are caused by "random" use of braces.

Let's pretend this were the code in question for a moment (using your suggestion of no braces):

Code:
for (i = 0 ; i < 6 ; i++ ) 
    System.out.print(" ") ; 

AllocateHugeMemoryBuffer();
Then we decide we didn't want to print that space so without looking carefully at the code we yank out that line:

Code:
for (i = 0 ; i < 6 ; i++ ) 

AllocateHugeMemoryBuffer();
Now we're allocating 6 huge memory buffers by accident.

Put the braces in there and it becomes a whole lot more difficult to make that mistake.

yeah, that's a simplistic example, but I've spent hours debugging code from stupid things like that.

Two braces aren't cluttering up the code. They are making it readable.

It's even more important around if statements. Doubly so if there is an else involved.
 

jeremy.king

macrumors 603
Jul 23, 2002
5,479
1
Fuquay Varina, NC
Wow, I could not disagree more. Some of the most annoying and difficult to spot bugs are caused by "random" use of braces.
Salty is right. This is clearly documented in the Java code conventions published by Sun.

http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html

"Braces are used around all statements, even single statements, when they are part of a control structure, such as a if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces."
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
Wow, I could not disagree more. Some of the most annoying and difficult to spot bugs are caused by "random" use of braces....
Two braces aren't cluttering up the code. They are making it readable.
You certainly have a point. But did you look at his code? There is a real issue here with redundant use and random placement of braces.

I'm OK with braces under and IF. I'm not OK with 2 sets of braces directly under an IF. My point was to de-clutter the program. Perhaps my example should have cited my point.

Todd
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
ok, ok! This is the example I should have used:

Code:
for (rows=1; rows<=6; rows++)
	{
		
		[color=red]{[/color]
                        System.out.print("***");
			
			[color=red]}[/color]
		System.out.print("   ");
	}
Call me a rogue programmer, but I have been known to omit the { } after an IF. The compiler hasn't complained once. :eek:

Yes, careless future editing could lead to a stupid mistake (as could any careless editing). Yes, the convention is there for a reason. No I am not submitting my code for a peer review. No this will not be a commericial endevour. No I am not getting graded. Yes I should play well with others and not suggest techniques that are contra-popular acceptable practices.

Grovel... grovel... grovel...
 

saltyzoo

macrumors 65816
Oct 4, 2007
1,065
0
ok, ok! This is the example I should have used:

Code:
for (rows=1; rows<=6; rows++)
	{
		
		[color=red]{[/color]
                        System.out.print("***");
			
			[color=red]}[/color]
		System.out.print("   ");
	}
Call me a rogue programmer, but I have been known to omit the { } after an IF. The compiler hasn't complained once. :eek:

Yes, careless future editing could lead to a stupid mistake (as could any careless editing). Yes, the convention is there for a reason. No I am not submitting my code for a peer review. No this will not be a commericial endevour. No I am not getting graded. Yes I should play well with others and not suggest techniques that are contra-popular acceptable practices.

Grovel... grovel... grovel...
LOL I agree with you on that one. that's not what you quoted originally. ;)
 

SilentPanda

Moderator emeritus
Oct 8, 2002
9,993
30
The Bamboo Forest
ok, ok! This is the example I should have used:

Code:
for (rows=1; rows<=6; rows++)
	{
		
		[color=red]{[/color]
                        System.out.print("***");
			
			[color=red]}[/color]
		System.out.print("   ");
	}
Call me a rogue programmer, but I have been known to omit the { } after an IF. The compiler hasn't complained once. :eek:
To be fair, the compiler won't complain about the above either but that doesn't make it "right"... :D

I won't say I follow the Sun specs to the letter but I try to abide by most of it... I've found it makes coding a lot easier in the long run. I'm sure you know that but for the new programmers (school seems to be kicking in with some projects now! Or at least I get that impression reading the forums lately).
 

MBP123

macrumors regular
Original poster
May 26, 2006
192
0
First, you should get rid of all your redundant { } pairs. For example, in this loop:

Code:
for (i = 0 ; i < 6 ; i++ ) 
{ 
      System.out.print(" ") ; 
}
you don't need the braces. There is only one clause to execute under the FOR, so simplify and de-clutter your program.

To make your program smaller, you can create methods to call to do repetitive tasks. For instance, create a method to print out a line of stars, and then call it 4 times. Create a method to print out "***bbb" (where "b" is a blank) across a line and call it 4 times. Create a method to print out "bbb***" across a line and call it 4 times too.

For the diamond, I worked it out using a line equation in slope/intercept form (y = mx - b, where y works out to be the number of stars to print each line, and x is the iteration number). I ended up with very tight code. Use a piece of graph paper to work it out. I started out by observing the following characteristics:

1) there are 36 columns, and the the diamond starts in the middle.
2) for each line printed, the number of spaces decreases by one, until the middle one is printed, then the number of spaces increases by one.
3) The count of stars printed each line has a pattern:
1, 3, 5, 7, 9, 7, 5, 3, 1
4) If I wanted to write a FOR loop, I would need a contiguous range of numbers that would peak in the middle. I decided on a range of -4 to 4. That gives 9 iterations, and using the absolute value method, I could achieve a peak in the middle. This range also happens to coincide perfectly on graph paper (although on graph paper, the diamond is sideways).

My total progam is 59 lines, with a blank line and a comment line around most lines of code.

Todd

Code:
************************************
***   ***   ***   ***   ***   ***   
***   ***   ***   ***   ***   ***   
   ***   ***   ***   ***   ***   ***
   ***   ***   ***   ***   ***   ***
************************************
                *
               ***
              *****
             *******
            *********
             *******
              *****
               ***
                *
************************************
   ***   ***   ***   ***   ***   ***
   ***   ***   ***   ***   ***   ***
***   ***   ***   ***   ***   ***   
***   ***   ***   ***   ***   ***   
************************************

we actually just learned about methods today, so my professor said using them is not of importance on this assignment. I think she wants us to do the diamond using just a for loop, and not y=mx+b. I think that doing %!=0 (determining that its odd) up to the value of 9 is more akin to what we are doing in class. But the professor only wants the system.out.print () to be one character, no more. So how would I get that, using a for loop, for the 1,3,5,7,9,7,5,3,1 stars?
 

MBP123

macrumors regular
Original poster
May 26, 2006
192
0
ah this is really frustrating me!

am i at least on the right track dividing by 2 to make sure its not even?

and i cant have the printout be more then 1 character which is frustrating too
 

Eraserhead

macrumors G4
Nov 3, 2005
10,410
10,855
UK
ah this is really frustrating me!

am i at least on the right track dividing by 2 to make sure its not even?

and i cant have the printout be more then 1 character which is frustrating too
OK, as this is a homework problem I'm not going to give you all the answers.

But the following code will print a "christmas tree" shape (EDIT: in the diamond section), its also not aligned correctly, but you should be able to work it out from there.

Code:
for(int i=0;i<9;i++){
	for(int j=0;j<10-i;j++){
		System.out.print(" ");
	}
	for(int j=0;j<(i*2+1);j++){
		System.out.print("*");
	}
	System.out.print("\n");
}
It produces the following:

Picture 2.png
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
If you can't figure out how to do the diamond in a single loop, don't. Break the problem down into 9 different problems.

The first problem being: "how to print 17 spaces, a star, and a newline?"

The second problem being: "how to print 16 spaces, 3 stars, and a newline?"

etc....

Todd
 

Gelfin

macrumors 68020
Sep 18, 2001
2,166
4
Denver, CO
I am an evil man. A bored, bored, evil man. Do not under any circumstances use this code.

Code:
public class test
{
  public static void main(String[] args)
  {
    for(int x = 0; x < 21; x++)
    {
      for(int y = 0; y < 36; y++)
      {
        System.out.print(((((x<11?x:20-x)<6)&&((x%5==0)||(((y/3)%2)^((x<11?x:20-x)<3?1:0))>0))||((x<11?x-6:14-x)+(y<16?y:32-y)>15))?"*":" ");
      }
      System.out.print("\n");
    }
  }
}
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
I am an evil man. A bored, bored, evil man. Do not under any circumstances use this code.

Code:
public class test
{
  public static void main(String[] args)
  {
    for(int x = 0; x < 21; x++)
    {
      for(int y = 0; y < 36; y++)
      {
        System.out.print(((((x<11?x:20-x)<6)&&((x%5==0)||(((y/3)%2)^((x<11?x:20-x)<3?1:0))>0))||((x<11?x-6:14-x)+(y<16?y:32-y)>15))?"*":" ");
      }
      System.out.print("\n");
    }
  }
}
You are a bored, evil and very sick man. LOL.

Todd
 

Phooto

macrumors member
Oct 30, 2007
83
1
I am an evil man. A bored, bored, evil man. Do not under any circumstances use this code.

Code:
public class test
{
  public static void main(String[] args)
  {
    for(int x = 0; x < 21; x++)
    {
      for(int y = 0; y < 36; y++)
      {
        System.out.print(((((x<11?x:20-x)<6)&&((x%5==0)||(((y/3)%2)^((x<11?x:20-x)<3?1:0))>0))||((x<11?x-6:14-x)+(y<16?y:32-y)>15))?"*":" ");
      }
      System.out.print("\n");
    }
  }
}
You can't be THAT bored - is this not possible?

Code:
public class test
{
  public static void main(String[] args)
  {
    for(int x = 0; x < 21; x++)
    {
      for(int y = 0; y < 36; y++)
        System.out.print(((((x<11?x:20-x)<6)&&((x%5==0)||(((y/3)%2)^((x<11?x:20-x)<3?1:0))>0))||((x<11?x-6:14-x)+(y<16?y:32-y)>15))?"*":" ");
      System.out.print("\n");
    }
  }
}
 

MBP123

macrumors regular
Original poster
May 26, 2006
192
0
Code:
 for(rows=0; rows<5; rows++){
    for (columns=18; columns<rows; columns--){
    
            System.out.print(" ");
            
    }
    for(columns=10; columns<18-rows*2-1; columns++){
            System.out.print ("*");
    }
       System.out.print("\n");
}
so i have it following the proper 7-5-3-1 shrinking format there, but its not properly aligned or spaced.
 

MBP123

macrumors regular
Original poster
May 26, 2006
192
0
So I think I got it!!!

Thanks for everyones help!


Code:
public class threes {
   public static void main( String[] args )
   {
	int rows, columns;
        
        for (rows=1; rows<=1; rows++)
	   {
		for (columns=1; columns<=36; columns++)
				{
				System.out.print("*");
				}
			System.out.print("\n");
			}//Initial row of 36 Asterisks
      
	
	for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("***");
			
			}
		System.out.print("   ");
	}
        
        System.out.print("\n");
        
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("***");
			
			}
		System.out.print("   ");
	}
        System.out.print("\n"); // Alternating 3 stars, and 3 spaces rows. 
        
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("   ");
                        
			
			}
		System.out.print("***");
	}
        System.out.print("\n");
        
        for (rows=1; rows<=6; rows++)
	{
		
		{
                        System.out.print("   ");
                        
			
			}
		System.out.print("***");
	}
        
	System.out.print("\n");
        
        for (rows=1; rows<=1; rows++)
	   {
		for (columns=1; columns<=36; columns++)
				{
					System.out.print("*");
				}
			
			}
        System.out.print("\n");// END OF FIRST SECTION
       
        

// BEGINNING OF DIAMOND SHAPE IN CENTER OF PRINT OUT
    for(rows=0; rows<5; rows++)
        {
            for(columns=0; columns<17-rows; columns++){
            
                System.out.print(" ");
            
    
        }
            for (columns=0; columns<(rows*2+1); columns++){
            System.out.print ("*");
        }
       
            System.out.print("\n");
        }//END OF FIRST PART OF DIAMOND SHAPE
        
   for( rows=0;rows<4;rows++){
            
            for( columns=0;columns<14+rows;columns++){

                System.out.print(" ");
	}
            for( columns=1;columns<9-rows*2-1;columns++){
	
		System.out.print("*");
	}
	System.out.print("\n");
        }
        //END OF SECOND PART OF DIAMOND SHAPE
     
    for (rows=1; rows<=1; rows++)// START OF SECOND SECTION OF PRINT OUT
	   {
            for (columns=1; columns<=36; columns++)
            {
		System.out.print("*");
            }
		System.out.print("\n");
            }
      
       
        for (rows=1; rows<=6; rows++)
	{
		
	{
                System.out.print("   ");
                        
			
	}
		System.out.print("***");
	}
        
	
        System.out.print("\n");
        
        for (rows=1; rows<=6; rows++)
	{
		
	{
                System.out.print("   ");
                        
			
	}
		System.out.print("***");
	}
        
	System.out.print("\n"); 
        
        for (rows=1; rows<=6; rows++)
	{
		
	{
                System.out.print("***");
			
	}
		System.out.print("   ");
	}
        
        System.out.print("\n");
        
        for (rows=1; rows<=6; rows++)
	{
		
	{
                 System.out.print("***");
			
	}
		 System.out.print("   ");
	}
        
                 System.out.print("\n");
         for (rows=1; rows<=1; rows++)
	   {
		for (columns=1; columns<=36; columns++)
				{
					System.out.print("*");
				}
			System.out.print("\n");
			}
        
	System.exit( 0 );   
   } // end main
} // end of program
 

toddburch

macrumors 6502a
Dec 4, 2006
748
0
Katy, Texas
FWIW, here is my version of the solution.

Of particular interest (to me, anyway!) is the diamond code.

Todd

Code:
public class diamond {

	static final int COLS    = 36 ; 
	static final String PAT1 = "***   " ; 
	static final String PAT2 = "   ***" ; 

   public static void main( String[] args ) {
		int rows, columns;
		int i ; 

		// print a line of stars 
		do_stars() ; 
		
		// Print PAT1, twice. 
		for ( i=0 ; i<2 ; i++) do_six_times(PAT1) ;

		// Print PAT2, twice 
		for ( i=0 ; i<2 ; i++) do_six_times(PAT2) ;

		// print a line of stars 
		do_stars() ; 
		
	    // DIAMOND SHAPE - calculated using slope/intercept form of a line equation.
		int x, y, spaces ; 
        
        for (x = -4 ; x <= 4 ; x++) { 
        	y = (-1 * Math.abs(x)) + 5 ;  // 2 slopes are -1 and 1. y= the # of stars on one side of the diamond 
        	spaces = ( COLS / 2 ) - y - 1 ;  // # of padding spaces 
        	for (i = 0 ; i < spaces    ; i++ ) System.out.print(" ") ;  // print spaces
        	for (i = 0 ; i < ((y*2)-1) ; i++ ) System.out.print("*") ;  // print stars 
        	System.out.print("\n") ; 
        } 

		// print a line of stars 
		do_stars() ; 
		
		// Print PAT2, twice 
		for ( i=0 ; i<2 ; i++) do_six_times(PAT2) ;

		// Print PAT1, twice. 
		for ( i=0 ; i<2 ; i++) do_six_times(PAT1) ;

		// print a line of stars 
		do_stars() ; 

	System.exit( 0 );   
	} // end main
   
	private static void do_six_times(String s) { 
		for (int i = 0 ; i < 6 ; i++ ) System.out.print(s) ; 
		System.out.print("\n") ; 
	}

	private static void do_stars() { 
		for (int i=0 ;  i < COLS ; i++ ) System.out.print("*");
		System.out.print("\n");
	} 
} 
// end of program
 

Similar threads

  • PinkyMacGodess
2
Replies
2
Views
401
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.