Program 1 - Triangles:
Write a Java application (Triangles.java) that displays the following triangle patterns side-by-side using nested while loops. Everything can be in main().
- Use class Scanner to read input.
- Allow the user to input the number of rows defining the size of the side-by-side triangles. No hardcoding or magic numbers in your code.
- Make sure your prompt and output messages match the sample prompt and messages word-for-word. - Each loop must be based on the current row number/iteration of the outer-most loop. - Hint: Treat each of the four triangle patterns as its own set of nested loops. Each row of each triangle pattern is made up of some number of individual '*' and ' ' (space) chars. - Note there is a space character between adjacent triangles.
To get a better understanding, if size of the triangle is 5, here’s the spacing (represented in a grid, for a clearer picture of the individual '*' and ' ' characters). * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - All asterisks ('*') and spaces (' ') must be printed a single character at a time using System.out.print( '*' ) or System.out.print( ' ' ) controlled by the nested while loops. No Strings! You are not allowed to use a String or StringBuilder or StringBuffer or any data structure to build each line to be output.
- Formatting is important for this program. If your output does not match the required output character-for-character, no credit will be awarded. Note there is no space at the end of each line.
- Only valid integers will be entered, but you must check for integers less than 2 and report the exact error message as shown in the example below.
Example Executions (user input in BOLD):
Example 1: java Triangles Enter the size of the triangles to display: 12 * ************ ************ * ** *********** *********** ** *** ********** ********** *** **** ********* ********* **** ***** ******** ******** ***** ****** ******* ******* ****** ******* ****** ****** ******* ******** ***** ***** ******** ********* **** **** ********* ********** *** *** ********** *********** ** ** *********** ************ * * ************
Example 2: java Triangles Enter the size of the triangles to display: -1 Triangle size must be > 1; Try again. Enter the size of the triangles to display: 0 Triangle size must be > 1; Try again. Enter the size of the triangles to display: 5 * ***** ***** * ** **** **** ** *** *** *** *** **** ** ** **** ***** * * *****
- 9 years ago
Purchase the answer to view it
- triangles.zip