I am trying to create a diamond shape in Java [duplicate] - java

This question already has answers here:
How to make a diamond using nested for loops
(19 answers)
Closed 2 years ago.
I currently have this code which allows me to create the left half of the diamond shape. Is there any way to mirror it to complete the right half. Or a completely different way of creating this shape.
public class diamond {
int size = 0; //sets a starting value for size
static int length = 9;
public static void main(String[] args) {
//creates half of our diamond shape :(
for (int i = 0; i < length; i++) {
int j = length - 1 - i;
for (int k = length / 2; k < length; k++) {
if (k == i || k == j || k == length + 7 + i - j)
System.out.print("X");
else
System.out.print(" ");
}
System.out.println("");
}
}
}

Here is another alternative that takes a slightly different approach.
Since certain widths or lines can't be specified exactly and always have a single middle line, this just prompts for a number.
It calculates spacing and adjusts the field of asterisks within two loops. The first does the top and middle line. The second just does the bottom portion.
String symb = "*";
Scanner input = new Scanner(System.in);
int max = 0;
while (max <= 1) {
System.out.print("Enter a positive no > 1: ");
max = input.nextInt();
}
System.out.println("Width and height are " + (2*max -3)+"\n");
for (int i = 1; i < max; i++) {
System.out.println(" ".repeat(max - i) + symb);
symb += "**";
}
for (int i = 2; i < max; i++) {
System.out
.println(" ".repeat(i) + symb.substring(2 * i));
}
When prompted for and provided an input of 5, this prints.
Enter a positive no > 1: 5
Width and height are 7
*
***
*****
*******
*****
***
*
You can modify this to produce the type of diamond you want.

Below code prints the diamond pattern as per your diagram. This program allows the user to input the no of rows for the diamond and also allows the user to select any shape you want to create your diamond with.
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
System.out.print("Enter Symbol : ");
char c = s.next().charAt(0);
drawDiamond(n,c);
}
static void drawDiamond(int n, char c) {
int i, j, space, k = 0;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
System.out.print(c);
else
System.out.print(" ");
k++;
}
k = 0;
System.out.println();
}
n--;
for (i = n; i >= 1; i--) {
for (j = 0; j <= n - i; j++) {
System.out.print(" ");
}
k = 0;
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
System.out.print(c);
else
System.out.print(" ");
k++;
}
System.out.println();
}
}
}
Sample Output :
Enter the number of rows: 4
Enter Symbol : *
*
* *
* *
* *
* *
* *
*

This Code draws a diamond like your picture but only works with odd numbers.
class Diamond{
int size = 0;
static int length = 9;
public static void main(String[] args) {
int outerSpace = length / 2; //number left to the first x
int count = outerSpace; //same number used to find the mid
int up = 0; //counter for the space between the xx
for (int i = 0; i < length; i++) {
if (i < count) { //this code gets used till you reach the middle
for (int j = 0; j < outerSpace; j++) { //prints space left of x
System.out.print(" ");
}
System.out.print("X");
for (int k = 0; k < up; k++) {
System.out.print(" "); //prints space between the x
}
System.out.println("X");
outerSpace--;
up += 2;
}else{ //code after middle
for (int j = 0; j < outerSpace; j++) {
System.out.print(" ");
}
System.out.print("X");
for (int k = 0; k < up; k++) {
System.out.print(" ");
}
System.out.println("X");
outerSpace++;
up -= 2;
}
}
}
}

To get the exact same design, The input length has to be even number.
public class Main {
private static int legnth = 10;
private static int x = legnth /2;
private static int y = x + 1;
public static void main(String[] args) {
for(int i=1; i <= legnth/2; i++) {
for(int j=1; j <= legnth; j++) {
if(j==x || j==y) {
System.out.print("*");
}else {
System.out.print(" ");
}
}
x--;
y++;
System.out.println("");
}
x+=2;
y-=2;
for(int i=1; i < legnth/2; i++) {
for(int j=1; j < legnth; j++) {
if(j==x || j==y) {
System.out.print("*");
}else {
System.out.print(" ");
}
}
x++;
y--;
System.out.println("");
}
}
}
output
**
* *
* *
* *
* *
* *
* *
* *
**

Here is another solution where you can create a string array for one fourth of the diamond and later manipulate that array to print it into diamond. It can take even or odd both to create a diamond like shape.
static int length=9;
static int n=length/2;
public static void main(String[] args) {
String []arr = new String[n];
for (int i = 0; i < n; i++) {
String space="";
int j = n - i;
for (int k = 0; k < j; k++) {
space=space+" ";
}
arr[i]=space+"X";
}
// To print upper half of diamond
for(int i=0;i<n;i++) {
String upper= arr[i] + arr[n -1 -i].substring(0,arr[n-1-i].length()-2)
+ arr[n -1 -i].substring(1,arr[n -1 -i].length());
System.out.println(upper);
}
// To print middle of the diamond
System.out.println("X" + arr[0].substring(0,arr[0].length()-1)
+arr[0].substring(0,arr[0].length()-1) + "X");
// To print down half of the diamond
for(int i=0;i<n;i++) {
String down= arr[n -1 -i]+arr[i].substring(0,arr[i].length()-2)
+arr[i].substring(1,arr[i].length());
System.out.println(down);
}
}

Here is another solution. It will work for any valid odd integer value given for length.
void createDiamond(int length) {
int n = length / 2;
for (int i = 0; i < length; i++) {
for (int j = 0; j <= length; j++) {
if ((i >= 0 && i <= n && (j == n - i || j == n + 1 + i))
|| (i > n && i < length && (j == i - n || j == length + n - i)))
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
}
}
Output:
createDiamond(9);
XX
X X
X X
X X
X X
X X
X X
X X
XX

Related

Java: Sudoku- increase number of empty spaces causes my code to throw an exception

I'm trying to make a Sudoku game for my project but if i increase the number of empty spaces in the Sudoku Grid the code just throws an exception arrayoutofbounds but can't figure out where it's coming from. k is the number of empty spaces in the grid.
I haven't tried anything because can't figure out what can be done at this kind of problem
Here is the code:
package sudoku.puzzle;
import java.util.*;
public class SudokuPuzzle {
int[] mat[];
int N; // number of columns/rows.
int SRN; // square root of N
int K; // No. Of missing digits
// Constructor
SudokuPuzzle(int N, int K) {
this.N = N;
this.K = K;
// Compute square root of N
Double SRNd = Math.sqrt(N);
SRN = SRNd.intValue();
mat = new int[N][N];
}
// Driver code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Select Level Of Difficulty \n 1.Easy\n 2.Medium\n 3.Hard");
String Choice = in .next(); in .close();
if ("1".equals(Choice) || "Easy".equals(Choice) || "easy".equals(Choice) || "e".equals(Choice) || "E".equals(Choice)) {
int N = 9, K = 40;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
if ("2".equals(Choice) || "Medium".equals(Choice) || "medium".equals(Choice) || "m".equals(Choice) || "M".equals(Choice)) {
int N = 9, K = 60;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
if ("3".equals(Choice) || "Hard".equals(Choice) || "hard".equals(Choice) || "h".equals(Choice) || "H".equals(Choice)) {
int N = 9, K = 72;
SudokuPuzzle sudoku = new SudokuPuzzle(N, K);
sudoku.fillValues();
sudoku.printSudoku();
}
}
// Sudoku Generator
public void fillValues() {
// Fill the diagonal of SRN x SRN matrices
fillDiagonal();
// Fill remaining blocks
fillRemaining(0, SRN);
// Remove Randomly K digits to make game
removeKDigits();
}
// Fill the diagonal SRN number of SRN x SRN matrices
void fillDiagonal() {
for (int i = 0; i < N; i = i + SRN)
// for diagonal box, start coordinates->i==j
fillBox(i, i);
}
// Returns false if given 3 x 3 block contains num.
boolean unUsedInBox(int rowStart, int colStart, int num) {
for (int i = 0; i < SRN; i++)
for (int j = 0; j < SRN; j++)
if (mat[rowStart + i][colStart + j] == num)
return false;
return true;
}
// Fill a 3 x 3 matrix.
void fillBox(int row, int col) {
int num;
for (int i = 0; i < SRN; i++) {
for (int j = 0; j < SRN; j++) {
do {
num = randomGenerator(N);
}
while (!unUsedInBox(row, col, num));
mat[row + i][col + j] = num;
}
}
}
// Random generator
int randomGenerator(int num) {
return (int) Math.floor((Math.random() * num + 1));
}
// Check if safe to put in cell
boolean CheckIfSafe(int i, int j, int num) {
return (unUsedInRow(i, num) &&
unUsedInCol(j, num) &&
unUsedInBox(i - i % SRN, j - j % SRN, num));
}
// check in the row for existence
boolean unUsedInRow(int i, int num) {
for (int j = 0; j < N; j++)
if (mat[i][j] == num)
return false;
return true;
}
// check in the row for existence
boolean unUsedInCol(int j, int num) {
for (int i = 0; i < N; i++)
if (mat[i][j] == num)
return false;
return true;
}
// A recursive function to fill remaining
// matrix
boolean fillRemaining(int i, int j) {
// System.out.println(i+" "+j);
if (j >= N && i < N - 1) {
i = i + 1;
j = 0;
}
if (i >= N && j >= N)
return true;
if (i < SRN) {
if (j < SRN)
j = SRN;
} else if (i < N - SRN) {
if (j == (int)(i / SRN) * SRN)
j = j + SRN;
} else {
if (j == N - SRN) {
i = i + 1;
j = 0;
if (i >= N)
return true;
}
}
for (int num = 1; num <= N; num++) {
if (CheckIfSafe(i, j, num)) {
mat[i][j] = num;
if (fillRemaining(i, j + 1))
return true;
mat[i][j] = 0;
}
}
return false;
}
// Remove the K no. of digits to
// complete game
public void removeKDigits() {
int count = K;
while (count != 0) {
int cellId = randomGenerator(N * N);
// System.out.println(cellId);
// extract coordinates i and j
int i = (cellId / N);
int j = cellId % 9;
if (j != 0)
j = j - 1;
// System.out.println(i+" "+j);
if (mat[i][j] != 0) {
count--;
mat[i][j] = 0;
}
}
}
// Print sudoku
public void printSudoku() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
System.out.print(mat[i][j] + " ");
System.out.println();
}
System.out.println();
}
}
What you got is probably a ArrayIndexOutOfBoundsException. That means at some point you try to access a field of an array outside its boundaries.
But I can´t see where K could be responsible for that. Can you provide more information about the error? E.g. at which value you get it or in which line.
EDIT: The variable i int the removeKDigits() function exceeds the boundaries of the array if the random generator spits out the value 81.

Output from second method not shown

I have developed a code to print 2 diamonds and the code is:
public class Diamond {
public static final int DIAMOND_SIZE = 5;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Diamond Height: " + DIAMOND_SIZE);
System.out.println("Output for: For Loop");
int noOfRows = DIAMOND_SIZE;
//Getting midRow of the diamond
int midRow = (noOfRows)/2;
//Initializing row with 1
int row = 1;
//Printing upper half of the diamond
for (int i = midRow; i > 0; i--)
{
//Printing i spaces at the beginning of each row
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
//Printing j *'s at the end of each row
for (int j = 1; j <= row; j++) {
System.out.print("* ");
}
System.out.println();
//Incrementing the row
row++;
}
//Printing lower half of the diamond
for (int i = 0; i <= midRow; i++) {
//Printing i spaces at the beginning of each row
for (int j = 1; j <= i; j++) {
System.out.print(" ");
}
//Printing j *'s at the end of each row
int mid = (row+1) / 2;
for (int j = row; j > 0; j--) {
if(i==0 && j==mid) {
System.out.print("o ");
}
else {
System.out.print("* ");
}
}
System.out.println();
//Decrementing the row
row--;
}
}
public static void diamond2() {
// writing the top portion of the diamond
int y = DIAMOND_SIZE;
int i = 1;
while (i < y + 1) {
int spaces = 0;
while (spaces < y - i) {
spaces++;
System.out.print(" ");
}
int j = i;
while (j > 0) {
j--;
System.out.print("* ");
}
System.out.println();
i++;
}
// writing the bottom half of the diamond
i = y - 1;
while (i > 0) {
int spaces = 0;
while (spaces < y - i) {
spaces++;
System.out.print(" ");
}
int j = i;
while (j > 0) {
System.out.print("* ");
j--;
}
System.out.println();
i--;
}
}
}
The result I get from this is:
Diamond Height: 5
Output for: For Loop
*
* *
* o *
* *
*
Which is from the first method, the output from the second method is not showing. When I comment out the first method then the output of the second method is showing. What am I doing wrong?
In order to access the chunk of code that is your second method, you need to formally call the method header. In your case, it can be done like so
diamond2();
Add this line of code into your main method where you would like that method to be called.

Printing a triangle in Java

I'm practicing basic coding exercises and trying to print the following triangle in Java:
*
***
*****
***
*
The following code gives me the results but I feel like there must be a much more elegant solution
for (int i = 1; i <= 5; i++) {
if (i % 2 == 1) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
for (int i = 3; i > 0; i--) {
if (i % 2 == 1) {
for (int j = 1; j < i + 1; j++) {
System.out.print("*");
}
System.out.println("");
}
}
Can anyone provide some insight into how to make this work in a better way?
Ok, here's some more code that produces the correct result that uses just the two for loops, but it looks even uglier:
for (int i = 1; i <= 10; i += 2) {
if (i <= 5) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
else if(i > 5 && i < 8){
for(int j = i/2; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
else{
for(int j = 1; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
}
First, you are skipping each 2nd iteration of the loop because you want to increase two steps at once. You can do this by changing the "i++" in your loop to "i += 2" and "i--" to "i -= 2", that will have the same effect and allows you to remove the if inside both loops.
Another improvement would be using a single outer loop and figuring out whether the inner loop should be increasing or decreasing the amount of asterisks. Maybe you can come up with an equation that gives you the amount of asterisks based on the value of i? (I didn't want to solve it completely so you have some exercise left, just comment if you want a full solution)
Updated with a solution that might be considered elegant as you can change the height of the triangle and there is no repetition:
int height = 5;
for (int i = 1; i <= 2 * height; i += 2) {
int numAsterisks;
if (i <= height) {
numAsterisks = i;
} else {
numAsterisks = 2 * height - i;
}
for (int j = 0; j < numAsterisks; j++) {
System.out.print("*");
}
System.out.println();
}
What about the following?
public void printTriangle(int size) {
int half = size / 2;
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
char[] a = new char[stars];
Arrays.fill(a, '*');
System.out.println(new String(a));
}
}
Or just a bit more optimized:
public void printTriangle(int size) {
int half = size / 2;
char[] a = new char[size];
Arrays.fill(a, '*');
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
System.out.println(new String(a, 0, stars));
}
}
for(int i = 0; i < 7; i++) {
for(int j = 0; j < i; j++) {
print("*");
}
print("\n");
}
This can be another solution to print a regular right triangle...
Here's a different way of looking at the problem. By using an integer array, I can solve lots of shape drawing problems by changing the values in the array.
When solving more difficult problems, you would use model classes instead of simple integers. The idea, however, is the same.
Here's the output.
*
***
*****
***
*
And here's the code:
public class Triangle {
public static void main(String[] args) {
int[] heights = {1, 3, 5, 3, 1};
for (int i = 0; i < heights.length; i++) {
for (int j = 0; j < heights[i]; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
How about...
int width = 5;
for (int i = 1; i <= width; i+=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
for (int i = width-2; i > 0; i-=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
Or, even better yet...
int width = 7;
double half = width / 2
for (int i = 0; i < width; i++){
System.out.println(String.format("%"+((i < half ? i : (width-i-1))*2+1)+"s", "").replaceAll(" ", "*"));
}
Gives
*
***
*****
***
*

How to make a diamond using nested for loops

So I was assigned to make a diamond with asterisks in Java and I'm really stumped. Here's what I've come up with so far:
public class Lab1 {
public static void main(String[] args) {
for (int i = 5; i > -5; i--) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int j = 0; j >= i; j--) {
System.out.print(" ");
}
System.out.println("*");
}
}
}
In order to make a diamond you need to set spaces and stars in shape. I have made this simple program using only nested loops since I am a beginner.
public class Diamond {
public static void main(String[] args) {
int size = 9,odd = 1, nos = size/2; // nos =number of spaces
for (int i = 1; i <= size; i++) { // for number of rows i.e n rows
for (int k = nos; k >= 1; k--) { // for number of spaces i.e
// 3,2,1,0,1,2,3 and so on
System.out.print(" ");
}
for (int j = 1; j <= odd; j++) { // for number of columns i.e
// 1,3,5,7,5,3,1
System.out.print("*");
}
System.out.println();
if (i < size/2+1) {
odd += 2; // columns increasing till center row
nos -= 1; // spaces decreasing till center row
} else {
odd -= 2; // columns decreasing
nos += 1; // spaces increasing
}
}
}
}
As you can see nos is the number of spaces. It needs to be decreased until the center row, and the number of stars needs to be increased but after the center row it's the opposite, i.e spaces increase and stars decrease.
size can be any number. I set it to 9 over here so I will have a size 9 star that is 9 rows and 9 columns max... number of space (nos) will be 9/2 = 4.5 .
But java will take it as 4 because int can not store decimal numbers and the center row will be 9/2 + 1 = 5.5, which will result in 5 as int.
So first you will make rows... 9 rows hence
(int i=1;i<=size;i++) //size=9
then print spaces like I did
(int k =nos; k>=1; k--) //nos being size/2
then finally stars
(int j=1; j<= odd;j++)
once the line ends...
You can adjust stars and spaces using an if condition.
for (int i = 0; i < 5; i++)
System.out.println(" *********".substring(i, 5 + 2 * i));
for (int i = 5; i > 0; i--)
System.out.println(" **********".substring(i - 1, 5 + (2 * i) - 3));
Note: Using Count Global variable we can manage space as well as star increment and decrement.
import java.util.*;
public class ParamidExample {
public static void main(String args[]) {
System.out.println("Enter a number");
Scanner sc = new Scanner(System.in);
int no = sc.nextInt();
int count = 1;
for (int i = 1; i <= 2 * no - 1; i++) {
for (int j = count; j <= no; j++) {
System.out.print(" ");
}
for (int k = 1; k <= count * 2 - 1; k++) {
System.out.print("* ");
}
if (i < no)
count++;
else
count--;
System.out.println("");
}
}
}
public class MyDiamond {
public static void main(String[] args) {
//Length of the pyramid that we want.151 is just an example
int numRows = 151;
//midrow is the middle row and has numRows number of *
int midrow = (numRows + 1) / 2;
int diff = 0;
for (int i = 1; i < numRows + 1; i++) {
for (int j = 1; j < numRows + 1; j++) {
if (((midrow - diff) <= j && (j <= midrow + diff))) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
if (i < midrow) {
diff++;
} else {
diff--;
}
}
}
}
public class Diamond {
//Size of the diamond
private int diagonal;
public Diamond(int diagonal) {
this.diagonal = diagonal;
}
public void drawDiamond() {
int n = diagonal;
for (int i = n / 2; i >= -n / 2; i--) {
for (int k = 0; k < i; k++) {
System.out.print(" ");
}
for (int j = 1; j <= (n - i * 2) && i >= 0; j++) {
System.out.print("*");
}
for (int k = 1; k <= -i && i < 0; k++) {
System.out.print(" ");
}
for (int j = (n / 2) * 2 + 2 * i; j >= -(n % 2 - 1) && i < 0; j--) {
System.out.print("*");
}
System.out.println();
}
}
public static void main(String[] args) {
//You pass diamond size here in the constructor
Diamond a = new Diamond(21);
a.drawDiamond();
}
}
The main problem is parity of diagonal.
If it's even you can't properly draw top asterisk. So there is 2 types of diamonds - with even and odd diagonal (with 2 and 1 asterisk at the top).
I can see what you are trying to do and this is a pretty neat way to think about the diamond.
You will have some issues with the j counter when i goes negative..look at how to use Math.abs()
Also try writing some pseudo code in basic steps with comments to get the pattern clear:
//print 5 spaces + 1 star
//print 4 spaces + 2 stars
//print 3 spaces + 3 stars
//print 2 spaces+ 4 stars
.
.
.
//print 5 spaces + 1 star
Then, literally substitute variables (j and i) for the numbers.
You now have a model. This is often the hardest part in programming..getting the model right. Only jump into coding when you have a good idea for how the model works.
Once you have the variables substituted, you can try to convert the whole thing into an automated loop.
import java.util.Scanner;
public class MakeDiamond {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Let's Creat Diamonds");
System.out.println("If number increases Diamonds gets bigger. Please input number lager than 1 : ");
int user_input = sc.nextInt(); //gets user's input
System.out.println("");
int x = user_input;
int front_space = -5;
for (int i = 0; i < 2 * user_input + 1; i++) {
for (int a = front_space; a < Math.abs(i - user_input); a++) {
System.out.print(" "); //Change a bit if diamonds are not in good shape
}
if (i < user_input + 1) {
for (int b = 0; b < 2 * i + 1; b++) {
System.out.print("* "); //Change a bit if diamonds are not in good shape
}
} else if (i > user_input) {
for (int c = 0; c < 2 * x - 1; c++) {
System.out.print("* "); //Change a bit if diamonds are not in good shape
}
x--;
}
System.out.print('\n');
}
System.out.println("\nRun Again? 1 = Run, 2 = Exit : ");
int restart = sc.nextInt();
System.out.println("");
if (restart == 2) {
System.out.println("Exit the Program.");
System.exit(0);
sc.close();
}
}
}
}
When making diamonds with while or for loops.
I think using 'Math.abs' will be the simplest way to make it.
You can put number by Scanner, and when input number increases diamonds will get bigger.
I used Eclipse to make this program.
so, the Space will be differ by your running environment. like another IDE, CMD or Terminal. if diamonds are not in good shape. Just change spaces.
package com.DiamondPrintingProgram;
import java.util.Scanner;
public class DiamondPrintingProgram {
public static void main(String[] args) {
int num = getInput();
int middle = (int) num / 2 + 1;
printOutput(num,middle);
}
public static int getInput() {
Scanner sc = new Scanner(System.in);
int num;
System.out.print("Enter a odd number: ");
while (true) {
num = sc.nextInt();
if (num % 2 != 0) {
break;
}
System.out.print("Please Enter a ODD NUMBER: ");
}
return num;
}
private static void printOutput(int num, int middle){
char asterisk = '*';
for (int j = 0; j < num; j++) {
for (int i = 1; i <= num; i++) {
if (j < middle) {
if ((i < (middle - j) || i > (middle + j))) {
System.out.print(' ');
} else {
System.out.print(asterisk);
}
} else {
if ((i < (j - middle + 2)) || (i > (2 * num - j - middle))) {
System.out.print(' ');
} else {
System.out.print(asterisk);
}
}
}
System.out.println();
}
}
}
I have the exact classwork in my university which also requires me to finish it in 3 for loops.
And this is how I did it.
In a simple way of explanation, I divide the diamond into two parts.
no. of lines
no. of spaces
no. of stars
total no. of slots
1
4
1
5
2
3
3
6
3
2
5
7
4
1
7
8
5
0
9
9
6
1
7
8
7
2
5
7
8
3
3
6
9
4
1
5
I want to find the no. of slots and the no. of spaces with each line, then allocating the no. of stars would be really easy.
And considering the no. of slots, line 1 - 5 and line 6 - 9 would become two separate groups(i.e. middleLine).
The equation of the no. of slots of the first half would be numberOfLines(i.e. i) + (middleLine - 1) where middleLine - 1 would be 4 when the maxNumberOfLines is 9.
The equation of the no. of slots of the last half would be middleLine(i.e. replacement of I) + (middleLine - 1)(i.e. same as above) - (i - middleLine) where i - middleLine would be -1 when i = 6.
And for the space, the first half would be middleLine - i and last half would be i - middleLine, which are exactly in a negative relationship(or symmetrical regarding their slopes).
public class printOutDiamondWith3Loops {
public static void main(String[] args) {
int userInput = 9;
double maxNumberOfLines = userInput;
// double type is used instead of integer type in order to prevent removal of remainder when a division performed.
double middleLine = Math.ceil(maxNumberOfLines/2);
// Print out the diamond.
for (int i = 1; i <= maxNumberOfLines; i++) {
// Determine the number of lines, which is also the maximum number of slots (the line in the middle).
if (i <= middleLine) {
// Separate the whole diamond into two parts(as mentioned above).
for (int j = 1; j <= i + ((middleLine - 1)); j++) {
// Determine the no. of slots in each line from line 1 to 5.
if (j <= middleLine - i) {
// Determine the no. of spaces and stars.
System.out.print(" ");
} else {
System.out.print("*");
}
}
} else { // i > middleLine
for (int k = 1; k <= (middleLine + (middleLine - 1)) - (i - middleLine); k++) {
// Determine the no. of slots in each line from line 6 to 9.
// For better understanding, I did not simplify the above condition.
// Noticeably, the first middleLine in above for loop is a replacement of i.
if (k <= i - middleLine) {
// Determine the no. of spaces and stars.
System.out.print(" ");
} else {
System.out.print("*");
}
}
}
System.out.println();
}
}
With such a framework, it is much easier to make further changes, such as letting the user input the no. of lines they want.
Hope this answer could help you.
I could lend you a more detailed version of my work, though not necessarily in need(the above explanation already explains the concepts): print-Out-Diamond-With-3-Loops-Advanced-Version.java
You can print a diamond of asterisks (mathematical operators) as follows:
int m = 4;
int n = 4;
for (int i = -m; i <= m; i++) {
for (int j = -n; j <= n; j++) {
int val = Math.abs(i) + Math.abs(j);
System.out.print(val > Math.max(m, n) ? " " : "∗");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
∗
∗ ∗ ∗
∗ ∗ ∗ ∗ ∗
∗ ∗ ∗ ∗ ∗ ∗ ∗
∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗
∗ ∗ ∗ ∗ ∗ ∗ ∗
∗ ∗ ∗ ∗ ∗
∗ ∗ ∗
∗
Try this
public class Main {
public static void main(String[] args) {
int n = 50;
int space = n - 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < space; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println("");
space--;
}
space = 0;
for (int i = n; i > 0; i--) {
for (int j = 0; j < space; j++) {
System.out.print(" ");
}
for (int j = 0; j < i; j++) {
System.out.print("* ");
}
System.out.println("");
space++;
}
}
}
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single statement inside a single loop.
public class Main {
public static void main(String[] args) {
final int MID_ROW_NUM = 5;
for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
System.out.println(" ".repeat(Math.abs(i)) + "*".repeat((MID_ROW_NUM - Math.abs(i)) * 2 - 1));
}
}
}
Output:
*
***
*****
*******
*********
*******
*****
***
*
By changing the space, you can also print a variant of the diamond:
public class Main {
public static void main(String[] args) {
final int MID_ROW_NUM = 5;
for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
System.out.println(" ".repeat(Math.abs(i)) + "* ".repeat((MID_ROW_NUM - Math.abs(i)) * 2 - 1));
}
}
}
Output:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
import java.util.Scanner;
public class Diamond {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int input = in.nextInt();
int min = 1;
for (int i = 0; i < input; i++) {
for (int j = input - 1; j > i; j--) {
System.out.print(" ");
}
for (int k = 0; k < min; k++) {
if (k % 2 == 0) {
System.out.print("*");
} else {
System.out.print(".");
}
}
min += 2;
System.out.println();
}
int z = input + input - 3;
for (int i = 1; i < input; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int k = 0; k < z; k++) {
if (k % 2 == 0) {
System.out.print("*");
} else {
System.out.print(".");
}
}
z -= 2;
System.out.println();
}
}
}
This should work. You probably only need most of the methods and printDiamond(_);
import java.util.Scanner;
public class StarsTry {
public static void main(String[] args) {
int reader;
Scanner kBoard = new Scanner(System.in);
do {
System.out.println("Insert a number of rows: ");
reader = kBoard.nextInt();
printDiamond(reader);
} while (reader != 0);
}
public static void printStars(int n) {
if (n >= 1) {
System.out.print("*");
printStars(n - 1);
}
}
public static void printTopTriangle(int rows) {
int x = 1;
for (int j = (rows - 1); j >= 0; j--, x += 2) {
printSpaces(j);
printStars(x);
System.out.print("\n");
}
}
public static void printSpaces(int n) {
if (n >= 1) {
System.out.print(" ");
printSpaces(n - 1);
}
}
public static void printBottomTriangle(int rows, int startSpaces) {
int x = 1 + (2 * (rows - 1));
for (int j = startSpaces; j <= (rows) && x > 0; j++, x -= 2) {
printSpaces(j);
printStars(x);
System.out.print("\n");
}
}
public static void printBottomTriangle(int rows) {
int x = 1 + (2 * (rows - 1));
for (int j = 0; j <= (rows - 1) && x > 0; j++, x -= 2) {
printSpaces(j);
printStars(x);
System.out.print("\n");
}
}
public static void printDiamond(int rows) {
printTopTriangle((int) rows / 2 + 1);
printBottomTriangle((int) rows / 2, 1);
}
}
import static java.lang.System.out;
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
sc.close();
Diamond d = new Diamond();
d.upperDiamond(row);
d.lowerDiamond(row - 2);
}
public void upperDiamond(int a) {
for (int i = 0; i < a; i++) {
for (int j = a - 1; j > i; j--)
out.print(" ");
for (int k = 0; k < 2 * i - 1; k++)
out.print("*");
out.print("\n");
}
}
public void lowerDiamond(int b) {
for (int i = 0; i < b; i++) {
for (int j = 0; j <= i; j++)
out.print(" ");
for (int k = 0; k < 2 * (b - i) - 1; k++)
out.print("*");
out.print("\n");
}
}
}
public class Main {
public static void main(String[] args) {
int number = 23,l =1,diff = 1,rem = number/2,rep = 0;
for(int i=1;i<=number;i++){
if(i < number/2 +1){
for(int k=rem;k>=1;k--)
System.out.print(" ");
for(int j=1;j<=l;j++)
System.out.print("*");
diff = 2;
rem -= 1;
}
if(i >= number/2 +1){
for(int k=0;k<rep;k++)
System.out.print(" ");
for(int j=1;j<=l;j++)
System.out.print("*");
diff =3;
rep += 1;
}
System.out.println();
l = diff == 2 ? (l + 2) : (l - 2);
}
}
}
//Suitable for only Odd numbers...
public class Main {
private static int l =1;
public static void main(String[] args) {
int number =9;
for(int i=1;i<=2*number -1;i++){
if(i<=number){
for(int j=1;j<=(number-i);j++)
System.out.print(" ");
for(int j=1;j<=i;j++)
System.out.print("* ");
}
if(i>number){
for(int j=1;j<=i-number;j++)
System.out.print(" ");
for(int j=1;j<=number-l;j++)
System.out.print("* ");
l += 1;
}
System.out.println();
}
}
}
class Inc_Dec {
public static void main(String[] args) {
int le = 11;
int c = 0;
int j1 = (le / 2) + 1;
int j2 = le - j1;
for (int i = 1; i <= le; i++) {
if (c < j1) {
for (int k = (j1 - i); k > 0; k--) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*" + " ");
}
c++;
System.out.println();
} else {
for (int k = (i - j1); k > 0; k--) {
System.out.print(" ");
}
for (int j = (le - i + 1); j > 0; j--) {
System.out.print("*" + " ");
}
System.out.println();
}
}
}
}
package practice;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
if (i <= 5) {
for (int k = 1; k <= 5 - i; k++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print(" *");
}
}
if (i > 5) {
for (int k = 0; k <= i - 6; k++) {
System.out.print(" ");
}
for (int j = 0; j <= 10 - i; j++) {
System.out.print(" *");
}
}
System.out.println();
}
}
}

Print an ASCII diamond of asterisks

My program that prints out a diamond like this:
...............*
..........* * *
.....* * * * *
* * * * * * *
.....* * * * *
..........* * *
...............*
But it only works if the parameter or each side of the diamond is 4. For example if I input 6, the spacing on the bottom triangle is wrong and I been trying to figure it out.
The bottom triangle doesn't change when the parameter is changed, only the top one does. It only works for input 4.
public static void printMoreStars(int n) {
int rowsPrime = 0;
for (int i = n + 1; i > 0; i--) {
for (int j = 0; j < (2 * i) - 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime += 1;
System.out.println(" ");
}
//bottom triangle
for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < (2 * i) + 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < rowsPrime; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime -= 2;
System.out.println(" ");
}
}
You made two mistakes when using rowPrimes. See my annotations below:
public class Stars {
public static void main(String[] args) {
printMoreStars(Integer.parseInt(args[0]));
}
public static void printMoreStars(int n) {
int rowsPrime = 0;
for (int i = n + 1; i > 0; i--) {
for (int j = 0; j < (2 * i) - 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) {
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime += 1;
System.out.println(" ");
}
rowsPrime -= 2; // <- middle line is already printed, so skip that
//bottom triangle
for (int i = 1; i < n + 1; i++) {
for (int j = 0; j < (2 * i) + 1; j++) {
System.out.print(" ");
}
for (int d = 0; d < (2 * rowsPrime) - 1; d++) { // <- changed condition to be the same as above
System.out.print("*" + " ");
}
System.out.println(); //new line character
rowsPrime--; // <- you have to decrease rowPrime by one.
System.out.println(" ");
}
}
}
To print a rhombus with dots on the left, you can use this code.
Try it online!
public static void main(String[] args) {
printRhombus(3);
}
public static void printRhombus(int n) {
for (int i = -n; i <= n; i++) {
// last element in the row
int last = n - Math.abs(i);
for (int j = -n; j <= last; j++)
if (Math.abs(i) + Math.abs(j) <= n)
System.out.print("*" + (j < last ? " " : ""));
else
System.out.print(".....");
System.out.println();
}
}
Output:
...............*
..........* * *
.....* * * * *
* * * * * * *
.....* * * * *
..........* * *
...............*
See also: Print a diamond shape with Java
Check This:
import java.io.*;
import java.lang.*;
import java.util.*;
class DiamondPattern {
static public int ReadInteger() {
try {
String inpString = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String s = reader.readLine();
return Integer.parseInt(s);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
public static void main(String[] args) {
System.out.println("Program for displaying pattern of *.");
System.out.print("Enter the maximum number of *: ");
int n = ReadInteger();
System.out.println("\nHere is the Diamond of Stars\n");
for (int i = 1; i <= n; i++) {
for (int j = 0; j < (n - i); j++)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
for (int k = 1; k < i; k++)
System.out.print("*");
System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 0; j < (n - i); j++)
System.out.print(" ");
for (int j = 1; j <= i; j++)
System.out.print("*");
for (int k = 1; k < i; k++)
System.out.print("*");
System.out.println();
}
System.out.println();
}
}

Categories