Print a diamond shape with Java - java

I want to print a grid shape on the output console in Eclipse.
Basically I took an integer from user that is the number of stars in a single border of the grid.
Here the code I have up to now:
public class PrintDiamond {
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
num--;
for (int i = num; i > 0; --i) {
//Insert spaces in order to center the diamond
for (int n = 0; n < i; ++n) {
System.out.print(" ");
}
System.out.print(" *");
for (int n = i; n < num; ++n) {
System.out.print(" + ");
System.out.print(" ");
}//Ending bracket of nested for-loop
System.out.println();
}//Ending bracket of for loop
//Print out a diamond shape based on user input
for (int i = 0; i <= num; ++i) {//<= to print the last asterisk
//Insert spaces in order to center the diamond
for (int n = 0; n < i; ++n) {
System.out.print(" ");
}
System.out.print(" *");
for (int n = i; n < num; ++n) {
System.out.print(" + ");
System.out.print(" ");
}//Ending bracket of nested for-loop
System.out.println();
}//Ending bracket of for loop
}
}
and the output is (for int. 6):
*
* +
* + +
* + + +
* + + + +
* + + + + +
* + + + +
* + + +
* + +
* +
*

Here is the code:
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
final char[][] diamond = makeDiamond(num);
for (int i = 0; i < diamond.length; i++) {
for (int j = 0; j < diamond[i].length; j++) {
System.out.print(diamond[i][j]);
}
System.out.println();
}
}
public static char[][] makeDiamond(int n) {
int width = 1 + 4 * (n - 1);
int height = 1 + 2 * (n - 1);
char[][] out = new char[height][width];
int x0 = 2 * (n - 1);
int y0 = n - 1;
for (int i = 0; i < width; i += 2) {
// Top borders
int y1 = Math.abs(y0 - i / 2);
out[y1][i] = '*';
// Bottom borders
int y2 = height - Math.abs(i / 2 - y0) - 1;
out[y2][i] = '*';
if ((x0 - i) % 4 == 0) {
// Plus signs
for (int j = y1 + 1; j < y2; j++) {
out[j][i] = '+';
}
}
}
return out;
}

Some hints for your solution:
Create a method for printing a "diamond row" for a given row width and a given total width of the diamond.
Create a tool method for printing a given number of spaces.
Your main method should have two simple loops: One for the upper, one for the lower half.
The magic is in the method of printing a single diamond row for the given two parameters w and n.
This is always a good approach - reduce your complex problem to a problem with lesser complexity - in this case, by creating methods and using these e.g. in loops.
In your method for printing a single diamond row, you will need to check if you are in an "odd" or "even" row.

Ok, this looks like a school asignment, so I won't write any code.
First you need to understand and write, in pseudo-code or just plain English, what you want to do:
Instructions on how to draw the grid.
How many lines should I print?
How long is each line?
How do I know if I have to print a + or not?
General steps of your program.
Read size of the grid, N.
If N < 1, ask again (or exit program).
If N = 1 or greater, print the grid.
Detailed sub-steps of your program.
Print the grid
Loop for number of lines.
Create empty array/buffer/list/string with correct length for current line.
...
Because right now, it seems like you haven't figured out any of that. And if that's the case, then your problem has nothing to do with Java but rather with basic programming knowledge, which you won't get if we just code the algorith for you.

Two nested for loops from -n to n and one if else statement. The zero point is in the center of a diamond, and the boundary is obtained when:
Math.abs(i) + Math.abs(j) == n
Try it online!
public static void main(String[] args) {
printDiamond(0);
printDiamond(2);
printDiamond(5);
}
static void printDiamond(int n) {
System.out.println("n=" + n);
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) + Math.abs(j) == n)
System.out.print("* ");
else if (Math.abs(i) + Math.abs(j) < n && j % 2 == 0)
System.out.print("+ ");
else
System.out.print(" ");
System.out.println();
}
}
Output (combined):
n=0
n=2
n=5
*
* * + * * + * * + * *
* * + * * + * * + + + * * + + + * * + + + + + * * + + + * * + + + * * + * * + * *
See also: Print an ASCII diamond of asterisks

Related

Trying to make a program where I roll 1 die 6 mil times while counting the amount of times it landed on each side. then displaying it decimal form

public class dice1 {
public static final int N = 6000000;
public static void main(String[] args) {
int[] d = new int[7];
for (int i = 1; i < 7; i++) d[i] = 0;
for (int k = 0; k < N; k++) {
int roll = (int)(6 * Math.random() + 1);
d[roll]++;
}
System.out.println("Rolls: " + N);
for (int i = 1; i < 7; i++) {
float decimal = d[i] / N;
System.out.print(" " + i + ": " + d[i]);
System.out.printf( ", " + i + " was rolled %f" , decimal);
System.out.println();
}
}
}
}
My problem is I have to display it in decimal form. For example on the side with 6 dots it could be 1 mil times out of 6 mil so the output should be like ".16". Mine ends up 0.00. Any tips?
Since both d[i] and N are ints, you're performing integer division, which only retains the "whole" part, left of the decimal point. Since d[i] is smaller than N, you're getting 0.
You could solve this by casting one of them to a floating point type, e.g.:
float decimal = ((float) d[i]) / N;
Or just define them like that to beging with.

I am trying to make a pattern (triangle in java)

I am trying to make this pattern in java:
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
This is the code which I have written:
package practise;
import java.util.Scanner;
public class PatternsUsingLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int j=1;j<=n;j++) {
for(int k=n;k>=1;k--) {
System.out.print("* ");
}
System.out.println();
}
}
}
please tell me the error
There are many ways to do it also to fix this issue. One of the simplest fixes is to replace the inner loop with the following:
for (int k = (n - j) + 1; k >= 1; k--)
Since you want to print n number of *s in the first line, n - 1 number of *s in the second line and so on, the value of k must be initialized to n when j is 1, n - 1 when j is 2 and so on.
Some of the other ways to do this requirement are as follows:
A.
for (int j = n; j >= 1; j--) {
for (int k = j; k >= 1; k--) {
System.out.print("* ");
}
System.out.println();
}
B.
for (int j = n; j >= 1; j--) {
for (int k = 1; k <= j; k++) {
System.out.print("* ");
}
System.out.println();
}
...and many more
You don't decrease the finish condition in inner loop. This will works:
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int row=0;row<n;row++) {
for (int column = 0; column < n-row; column++) {
System.out.print("* ");
}
System.out.println();
}
The problem is that you haven't tried debugging your code.
To debug your code try printing out the variables that you are using at the beginning of each line to see if they are what you expect. You have (hopefully) thought about the code, and what you think each variable will be on each line, so you've missed something, you have a bug.
For example try this:
package practise;
import java.util.Scanner;
public class PatternsUsingLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int j=1;j<=n;j++) {
System.out.print("j: " + j + " n: " + n);
for(int k=n;k>=1;k--) {
System.out.print("* ");
}
System.out.println();
}
}
}
When you run that you get
j: 1 n: 5* * * * *
j: 2 n: 5* * * * *
j: 3 n: 5* * * * *
j: 4 n: 5* * * * *
j: 5 n: 5* * * * *
Which shows what a couple of the other answers are pointing out, that n doesn't change so the output is always 5 stars.
Now you can figure out the answer. (Hint: start j from 0 and use k=n-j)
Its a very small mistake that you are doing , the first loop is correct but in the inner loop you are printing n stars again (from n to 1).
You need to print (n - i + 1) stars for every loop.
Use this change :
...
...
int n = sc.nextInt();
for(int j=1;j<=n;j++) {
for(int k=n-j+1;k>=1;k--) {
System.out.print("* ");
}
System.out.println();
}
...
...
//... means same code //

Pascal's triangle generalized formula derivation

class Solution {
public static void main(String[] argh) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int number = 1;
System.out.format("%" + (t - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
// how this formula was derived ???
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
The only thing I want to know is that how the formula for generating each element was derived, it works perfect but how?
number = number * (i - j) / (j + 1)
Just want to derive such expressions in similar questions.
Each row of Pascal's triangle is generated by iterating through the binomial coefficient function, nCr:
Lets compare this to nCr+1:
The second factor on the second line is exactly the factor (i - j) / (j + 1) which you multiply by to obtain the next number in the row. In the code j = r, i = n.

Printing a rectangle - I want an additional print but I can't get it work

Made an own task for me to learn programming in java, about printing in particular.
As example, we have input 8. Then we must get as output a rectangle made of "+", so it would look like this:
++++++++
+ +
+ +
+ +
+ +
+ +
+ +
+ +
++++++++
The following code will do this (if you want me to explain it, please tell me and I will do it):
public class Printest{
public static void main(String[] args){
int x = Integer.parseInt(args[0]);
for(int i=0; i<x; i++){
System.out.print("+");
}
System.out.println("");
for(int i=0; i<x-1; i++){
System.out.print("+");
for(int j=0; j<x-2; j++){
System.out.print(" ");
}
System.out.print("+");
System.out.println("");
}
for(int j=0; j<x; j++){
System.out.print("+");
}
}
}
But now I want add an additional feature so there is a cross inside of this square, how can I do it? I have tried to add some if-statements but I always ended up shifting the rectangles left and right edges.. : /
I want it looks like this to be more precise:
+++++++++
+* *+
+ * * +
+ * * +
+ * +
+ * * +
+ * * +
+* *+
+++++++++
How would you do it? if-statements doesn't seem to work and I have the feeling it's not possible to implement this in my code because of the multiple, separate for-loops..?
By the way, is there maybe a much easier way to get this work (just print the rectangle)? I think I took a very complicated and unefficient way. I would be very interested in knowing easier ways, if they aren't more complicated :P
By the way, is there maybe a much easier way to get this work (just print the rectangle)? I think I took a very complicated and unefficient way.
Actually yes! You can do it with 2 for loops:
public class RectangleWithShapesExample {
public static void main(String[] args) {
int number = 8;
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
if (i == 0 || i == number - 1) {
System.out.print("+");
} else {
if (j == 0 || j == number - 1) {
System.out.print("+");
} else {
System.out.print(" ");
}
}
}
System.out.println("");
}
}
}
That alone, prints the rectangle of size 8, then, if you add this else-if statement:
else if (i == j || i == (number - j - 1)) {
System.out.print("*");
}
The first condition above tells your program to print a * diagonal like this: \ (that orientation), and the second one, evaluates it to print it in the other direction (/)
You can print the * cross, so, in the end your whole program looks like this:
public class RectangleWithShapesExample {
public static void main(String[] args) {
int number = 9;
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
if (i == 0 || i == number - 1) {
System.out.print("+");
} else {
if (j == 0 || j == number - 1) {
System.out.print("+");
} else if (i == j || i == (number - j - 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
System.out.println("");
}
}
}
And it's output is:
++++++++
+* *+
+ * * +
+ ** +
+ ** +
+ * * +
+* *+
++++++++
And with 9 elements:
+++++++++
+* *+
+ * * +
+ * * +
+ * +
+ * * +
+ * * +
+* *+
+++++++++
As a suggestion, I recommend you to space a little your operation signs from your variables to make your code a little more readable and make your variables more descriptive (x to number for example)
You need to find relationships between the corners of the cross/star. Take this star for example of size 5.
0 1 2 3 4
0 * *
1 * *
2 *
3 * *
4 * *
In a cross in the diagonal from (0,0) to (4,4), indices are the same (in the code this means row == col).
Also, you can notice that in the diagonal from (0,4) to (4,0) indices always sum up to 4, which is size - 1 (in the code this is row + col == size - 1).
Therefore in the code, you will need to loop through rows and then through columns. Each time you have to check if the above conditions are fufilled.
For the + border simply check when either row or col is 0, and also when equal to size - 1.
Lastly you print the border first so the corners of the cross are not * but rather +.
Code:
class Main {
public static void main(String[] args) {
printCross(8); //Vertical size of rectangle/cross
}
public static void printCross(int size) {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (row == 0 || col == 0 || row == size - 1 || col == size - 1)
System.out.print('+');
else if (row == col || row + col == size - 1)
System.out.print('*');
else
System.out.print(" ");
}
System.out.println();
}
}
}
Try it here!

I can't wrap my head around the "draw some stairs with stick-men" program

You've probably seen it before in a Java 1 class: it's a problem that asks you write a program that draws the following figure:
I have to use a constant. I am not allowed to use anything but for-loops, print, and println. No parameters, no arrays. I know how I could do it with parameters and arrays, lucky me. Any help is appreciated!
Here is my incomplete code:
public class Stairs {
public static final int LENGTH=5;
public static void main(String[] args) {
printStairs();
}
public static void printStairs() {
for (int allStairs=1; allStairs<=15; allStairs++) {
for (int spaces=1; spaces<=(-5*allStairs+30); spaces++) {
System.out.print(" ");
}
for (int stair = 1; stair <= 5; stair++) {
System.out.println(" o *******");
}
}
}
}
This sounds like a homework question, so I don't just want to give you the answer, but try breaking it down into steps. Think about the things that you know:
1) Every stickman has this shape:
o ******
/|\ *
/ \ *
2) You can print this out using the following code:
System.out.println(" o ******");
System.out.println(" /|\ * ");
System.out.println(" / \ * ");
3) You can print multiple by using a loop:
for (int stair = 1; stair <= LENGTH; stair++) {
System.out.println(" o ******");
System.out.println(" /|\ * ");
System.out.println(" / \ * ");
}
Think about what kind of output this would give you, and what needs to be changed. Realize that each stickman needs to be indented a certain amount. Figure out how to indent them appropriately based on the value of stair.
You can look at the figure and observe that each stickman has 3 lines, for each line:
Spaces, if necessary, proportionate to the number of stickmen
Part of the stick man - you can hard code this
The flat surface of 6 *, or one * followed by 5 spaces
Spaces, if necessary, proportionate to the number of stickmen
A *
And at the end, the last line is * proportionate to the number of stickmen.
Here is my final final attempt using formatting.
public static void main(String[] args) {
int steps = 5;
for (int x = 0; x < steps; x++) {
System.out.format(((steps == (x + 1)) ? "" : ("%"
+ ((steps - x - 1) * 5) + "s"))
+ " o ******"
+ ((x == 0) ? "" : ("%" + (x * 5) + "s"))
+ "*\n", " ", " ");
System.out.format(((steps == (x + 1)) ? "" : ("%"
+ ((steps - x - 1) * 5) + "s"))
+ " /|\\ * "
+ ((x == 0) ? "" : ("%" + (x * 5) + "s"))
+ "*\n", " ", " ");
System.out.format(((steps == (x + 1)) ? "" : ("%"
+ ((steps - x - 1) * 5) + "s"))
+ " / \\ * "
+ ((x == 0) ? "" : ("%" + (x * 5) + "s"))
+ "*\n", " ", " ");
}
for (int i = 0; i < (steps + 1) * 5 + 2; i++) {
System.out.print("*");
}
}
Output:
o *******
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
********************************
\o/
The approach below is also funny (depending on your humor preferences), but not a complete solution:
for (String s = " o ***** /|\\ * / \\ * "; s
.charAt(8) != '*'; s = s.substring(5, s.length() / 3) + " "
+ s.substring(s.length() / 3 + 5, 2 * s.length() / 3) + " "
+ s.substring(2 * s.length() / 3 + 5, s.length()) + " ") {
System.out.println(s.substring(0, s.length() / 3) + "*");
System.out
.println(s.substring(s.length() / 3, 2 * (s.length() / 3))
+ "*");
System.out.println(s.substring(2 * (s.length() / 3), s.length())
+ "*");
}
Output:
o ******
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
There is a recursive block with diminishing white space. The recursion ends at LEFT_SPACE == 0 The recursive block is
LEFT_SPACE o ******RIGHT_SPACE*
LEFT_SPACE/|\ * RIGHT_SPACE*
LEFT_SPACE/ \ * RIGHT_SPACE*
Here are some tips:
You should think about it horizontally.
your main loop must be stairs amount related because you are bound by the number of stairs you have to draw.
It will probably be easiest to print each line separately, so understand all the information you need to draw each line.
Here is what I ultimately ended up with:
public class Stairs {
public static final int LENGTH=5;
// The 'main method' prints out all the stairs with the appropriate indentations.
public static void main(String[] args) {
// outer loop
for (int allStairs=0; allStairs<=4; allStairs++) {
// first nested loops print the heads and tops of steps
for (int spaces=1; spaces<=(-5*allStairs+20); spaces++) {
printSpace();
}
System.out.print(" o ******");
for (int backWall=0; backWall<allStairs*(LENGTH); backWall++) {
printSpace();
}
printStar();
// second nexted loops print the body and the backs of the stairs
for (int spaces = 1; spaces <= (-5 * allStairs + 20); spaces++) {
printSpace();
}
System.out.print(" /|\\ *");
for (int backWall=1; backWall<=LENGTH*(allStairs+1); backWall++) {
printSpace();
}
printStar();
// third nested loops print the legs and lower backs of stairs
for (int spaces = 1; spaces <= (-5 * allStairs + 20); spaces++) {
printSpace();
}
System.out.print(" / \\ *");
for (int backWall=1; backWall<=LENGTH*(allStairs+1); backWall++) {
printSpace();
}
printStar();
}
// this loop prints the very bottom line of stars
for (int lastLine=1; lastLine<=32; lastLine++) {
System.out.print("*");
}
System.out.println();
}
// printSpace() prints out a space
public static void printSpace() {
System.out.print(" ");
}
// printStar() prints out an asterisk
public static void printStar() {
System.out.println("*");
}
}
I did it slightly differently. The following script will work with any number of stairs. I've commented it so you should know exactly what I am doing.
public class stairman {
//establishing class constants
public static final int STAIR_NUM = 5;
public static final int WIDTH = STAIR_NUM * 5;
public static void main(String[] args) {
//perform this loop for as many times as there are stairs
for (int i=1; i<=STAIR_NUM; i++) {
//calculating number of spaces before the top line of the stair
for (int x=1; x<=(WIDTH+(i*(-5))); x++) {
System.out.print(" ");
}
//printing top line of the stair
head();
//calculating the number of spaces after the top line of the stair
for(int y=1; y<=((i-1)*5); y++){
System.out.print(" ");
}
System.out.println("*");
//calculating the number of spaces before the 1st middle line of the stair
for (int x=1; x<=(WIDTH+(i*(-5))); x++) {
System.out.print(" ");
}
//print the first middle line of the stair
middle1();
//calculating the number of spaces after the 1st middle line of the stair
for (int y=1; y<=(i*5); y++){
System.out.print(" ");
}
System.out.println("*");
//calculating the number of spaces before the 2nd middle line of the stair
for (int x=1; x<=(WIDTH+(i*(-5))); x++) {
System.out.print(" ");
}
//printing the 2nd middle line of the stair
middle2();
//calculating the number of spaces after the 2nd middle line of the stair
for (int y=1; y<=(i*5); y++){
System.out.print(" ");
}
System.out.println("*");
}
//calculating the number of stars needed for the bottom of the stairs
for (int z=1; z<=(WIDTH+7); z++) {
System.out.print("*");
}
}
public static void head() {
System.out.print(" o ******");
}
public static void middle1() {
System.out.print(" /|\\ *");
}
public static void middle2() {
System.out.print(" / \\ *");
}
}
I tested the above code and it wasn't working for me. So I had a go at it and used some of their ideas.
public class DrawStairs {
public static final int HEIGHT= 5;
public static final int TOTALHEIGHT= HEIGHT*5;
public static void main(String[] args){
//Main Outer Loop
for(int i=1; i<=HEIGHT; i++){
//Loop for the spaces before, then print the head
for(int j=1; j<=TOTALHEIGHT+(i*(-5)); j++){
System.out.print(" ");
}
printTop();
//Loop for spaces after, then print asterisk
for(int j=1; j<=(i-1)*5; j++){
System.out.print(" ");
}
System.out.println("*");
//Loop for the spaces before, then print the body
for(int j=1; j<=TOTALHEIGHT+(i*(-5)); j++){
System.out.print(" ");
}
printMiddle();
//Loop for spaces after, then print asterisk
for(int j=1; j<=(i-1)*5; j++){
System.out.print(" ");
}
System.out.println("*");
//Loop for spaces before, then print the legs
for(int j=1; j<=TOTALHEIGHT+(i*(-5)); j++){
System.out.print(" ");
}
printBottom();
//Loop for spaces after, then print asterisk
for(int j=1; j<=(i-1)*5; j++){
System.out.print(" ");
}
System.out.println("*");
}
// for loop for printing the floor of asterisks
for(int i=1; i<= TOTALHEIGHT+7; i++){
System.out.print("*");
}
}
public static void printTop() {
System.out.print(" o ******");
}
public static void printMiddle() {
System.out.print(" /|\\ * ");
}
public static void printBottom() {
System.out.print(" / \\ * ");
}
}

Categories

Resources