How to make a pyramid using astersik in Java? - java

Good day guys! So I'm self learning java right now. And one of the exercises I'm answering now is creating a program Pyramid.java that takes an input N and prints a
pyramid whose each side is of length N, like the one below: My problem is that everytime I put an input on the command line, the 3 asterisk in the middle don't appear.
*
* *
* * *
* * * *
* * * * *
Here's my code
public class D2Q6 {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int k = 1;
for(int i = 1; i <= N; i++) {
for(int j = 0; j < N-i; j++)
System.out.print(" ");
System.out.print("*");
if(i > 1) {
if(i == N) {
for(int j = 0; j < i-1; j++)
System.out.print(" *");
}
else {
for(int j = 0; j < k; j++)
System.out.print(" ");
k = k+2;
System.out.print("*");
}
}
System.out.println();
}
}

I presume you are trying to execute your program through eclipse or some editor with its own console. The issue might not be with the program, but with the font (type and size) used in console.
Try running the program in DOS prompt, and you might be able to see your desired outcome.
public class PrintPyramidStar
{
public static void main(String args[])
{
int c = 1;
for (int i = 1; i <= 8; i++)
{
for (int j = i; j < 8; j++)
{
System.out.print(" ");
}
for (int k = 1; k <= c; k++)
{
if (k % 2 == 0)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
c += 2;
}
}
}
Above is a random star program I picked using search. Running the same via eclipse console gave me skewed triangle, wherein running the same via windows command prompt gave me a perfect triangle.

I stepped through your program in Eclipse and thought the problem might be here. Currently this is printing a blank space.
else {
for(int j = 0; j < k; j++)
System.out.print(" ");
k = k+2;
System.out.print("*");
}
If you change it to the below, it prints solid asterisk then an extra one at the end;
else {
for(int j = 0; j < k; j++)
System.out.print("*");
k = k+2;
System.out.print("*");
}
However I assume that you are going for a '* * *' kind of thing, but hopefully that narrows it for you.

I would start by creating two methods, one to get the spaces and one to get the asterisks. Something like,
private static String getNSpaces(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(' ');
}
return sb.toString();
}
private static String getNAsterisks(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (i != 0) {
sb.append(' ');
}
sb.append('*');
}
return sb.toString();
}
Then your main method can be as simple as -
for (int i = 1; i <= N; i++) {
System.out.print(getNSpaces(N - i));
System.out.println(getNAsterisks(i));
}
When I run the above with N equal to 5 I get
*
* *
* * *
* * * *
* * * * *

I thought I would post an alternative, brief approach to this common programming exercise.
public static void main(String args[]) {
System.out.println(pyramid(Integer.parseInt(args[0])));
}
public static String pyramid(int size) {
return line(size, size);
}
public static String line(int max, int size) {
return size < 1 ? "" : line(max, size - 1) + copies(" ", max - size) + copies("* ", size) + '\n';
}
public static String copies(String s, int size) {
return size < 1 ? "" : String.formatîui("%0" + size + "d", 0).replace("0", s);
}
See live demo
This uses recursion and breaks the code up into meaningful methods that each have their own task that is accomplished in one line.
This is not a high performance solution, but would be fast enough for moderate sizes. It is written for readability and method cohesion.

Related

i want to figure out what's wrong in my code

I want to make a java pattern like this using while loops
* * * *
* * *
* *
*
and here is my code
int i = 4;
int j = 0;
while (i >= 0) {
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.print("\n");
i--;
}
but its giving output like this:
* * * *
Does anyone knows what to do....?
TRY CONSIDERING THIS ONE MIGHT HELP YOU !!
Using FOR Loop
public class DownwardTrianglePattern {
public static void main(String[] args) {
int rows = 4;
//outer loop
for (int i = rows-1; i >= 0 ; i--) {
//inner loop
for (int j = 0; j <= i; j++) {
//prints star and space
System.out.print("*" + " ");
}
//throws the cursor in the next line after printing each line
System.out.println();
}
}
}
Using While Loop
public class Itriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter N : ");
int n = sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
int i = n, j;
while(i > 0) {
j = 0;
while(j++ < i) {
System.out.print(c);
}
System.out.println();
i--;
}
}
}
After i--;
you can j=0;
The problem in your code is that in first iteration after completing both the while loops the value of variables is i=3 and j=4. So for the next iteration the first while loop will run as the condition is true i.e. 3>=0 but for the next while loop the condition will be false as j i.e. 3 not less than i i.e. 3. So that's why the next loop does not executes and you are getting that output.
The j needs to be initialized inside loop.
I changed the code as below. it's giving correct output
int i = 4;
while (i >= 0) {
int j = 0;
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.print("\n");
i--;
}
please reset j after j loop
int i = 4;
int j = 0;
while (i >= 0) {
while (j < i) {
System.out.print(" * ");
j++;
}
j = 0;
System.out.print("\n");
i--;
}
when you're finished with inner loop you have to reset j value else it's value will remain 4 which is not less then i value. you can reset the value before starting inner while
int i = 4;
int j = 0;
while (i >= 0) {
j = 0;
while (j < i) {
System.out.print(" * ");
j++;
}
System.out.println(""); // println will work same as System.out.print("\n") in this scenario
i--;
}
By the way your problem can be nicely solved using recursion
public static void main(String[] args) {
printLine(4);
}
private static void printLine(int numberOfStars) {
if(numberOfStars == 0) {
return;
}
System.out.println("* ".repeat(numberOfStars));
printLine(numberOfStars - 1);
}
Output
* * * *
* * *
* *
*

Printing Christmas Tree task in Java prints two different results with the exact same identical code

Can someone help me solve the bellow?
I have attached two codes. Both should be identical from my comparison. One of them prints almost normal Xmas Tree (Code 2/Result Code 2) and the other one (Code 1/Result Code 1) prints only the right side of the tree. I do not understand why and how is this possible....
Also, can someone explain to me the process of how the code works? I understand it only a little bit. Still learning and I copied Code 2 and tried to replicated manually with Code 1.
Code 1:
public class XmasTree {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How tall do you want it?");
int height = input.nextInt();
for (int i = 0; i < height; i++) {
for (int j = 0; j < height -i; j++);{
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
for (int i = 0; i <= height; i++){
for (int j = 0; j <= height; j++){
System.out.print(" ");
}
for (int k = 1; k < 2; k++){
System.out.print("*");
}
System.out.println();
}
input.close();
}
}
Code 2:
public class XmasTree2 {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("How tall do you want your tree to be?");
int height = input.nextInt();
for(int i = 0; i < height; i++){
for(int j = 0; j < height - i; j++){
System.out.print(" ");
}
for(int k = 0; k <= i; k++){
System.out.print("* ");
}
System.out.println();
}
for(int i = 0; i <= height; i++){
for(int j = 0; j <= height; j++){
System.out.print(" ");
}
for(int k = 1; k < 2; k++){
System.out.print("*");
}
System.out.println();
}
input.close();
}
}
Result Code 1:
How tall do you want it?
4
*
* *
* * *
* * * *
*
*
*
*
*
Result Code 2:
How tall do you want your tree to be?
4
*
* *
* * *
* * * *
*
*
*
*
*
You have an extra ; after your second for-loop.
Do you want to know how I discovered that? I put your code in an IDE and let it auto-format it for me. That way the mistake becomes clear.
This is why correct formatting is so important.

Having trouble making it look like an actual diamond

My code works I just want to know what to do to get it to actually look like a diamond. Everything is just left justified like this:
*
* *
* * *
* * *
* *
*
But I want it to look like this:
*
* *
* * *
* * *
* *
*
public static void s3(int num, int len)
{
for(i = 1; i<=num; i++)
System.out.print(" " + "*");
System.out.print(" ");
System.out.println();
if(num < len)
s3(num + 1, len);
for (j = 1; j<= num; j++)
System.out.print(" " + "*");
System.out.print(" ");
System.out.println();
}
}
should I use print f to format or what? I've had a long day of frustrating programming and just need some help. Thanks!
The solution is not really a beauty, but it's 4am here and that's all I can provide for now ;)
About recursion you are very welcome to think how you can do it on your own.
public static void s3(int len) {
for (int i = 0; i <= len; i++) {
for (int j = len; j > i; j--) {
System.out.print(" ");
}
for (int j = 0; j < len - (len - i); j++) {
System.out.print(" *");
}
System.out.println("");
}
for (int i = 0; i <= len; i++) {
for (int j = 0; j < (i); j++) {
System.out.print(" ");
}
for (int j = len; j > i; j--) {
System.out.print(" *");
}
System.out.println("");
}
}

Printing a diamond - can't enter input?

I'm trying to write a program that outputs a diamond pattern like this:
*
***
*****
***
*
I've started by trying to first get it to print the top half of the diamond.
I can input the 'totalLines' into the console, but I can't type anything when it prompts for 'character'. Why would this be happening?
We've been using JOptionPane for most of our assignments, so it makes sense that I'd be having trouble with this, but from what I can tell from reading the book, this is correct.
(And if you have time to talk to me about the for-loops, I'm pretty sure they need work. I'd be very grateful.)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int totalLines, lines, currLine = 1, spaces, maxSpaces, minSpaces, numCharacters, maxCharacters, minCharacters;
String character;
System.out.print("Enter the total number of lines: ");
totalLines = input.nextInt();
System.out.print("Enter the character to be used: ");
character = input.nextLine();
lines = ((totalLines + 1)/2);
// spaces = (Math.abs((totalLines + 1)/2)) - currLine;
maxSpaces = (totalLines + 1)/2 - 1;
minSpaces = 0;
// numCharacters = (totalLines - Math.abs((totalLines +1) - (2*currLine)));
maxCharacters = totalLines;
minCharacters = 1;
spaces = maxSpaces;
for (currLine = 1; currLine<=lines; currLine++) {
for (spaces = maxSpaces; spaces<=minSpaces; spaces--){
System.out.print(" ");
}
for (numCharacters = minCharacters; numCharacters>= maxCharacters; numCharacters++){
System.out.print(character);
System.out.print("\n");
}
}
}
Try using next() instead of nextLine().
I'm creating a separate answer in regards to your for loops. This should be pretty close to what you need.
StringBuilder might be new to you. Because StringBuilder is mutable and String is not, if you're doing multiple concatenations onto an existing string it's usually preferable to use StringBuilder instead of String. You don't have to use StringBuilder for this exercise but it's a good habit to start.
//Get user input here
int lines = totalLines;
if(totalLines % 2 != 0)
lines += 1;
int i, j, k;
for (i = lines; i > 0; i--)
{
StringBuilder spaces = new StringBuilder();
for (j = 1; j < i; j++)
{
spaces.append(" ");
}
if (lines >= j * 2)
{
System.out.print(spaces);
}
for(k = lines; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}
for (i = 2; i <= lines; i++)
{
StringBuilder spaces = new StringBuilder();
System.out.print(" ");
for (j = 2; j < i; j++)
{
spaces.append(" ");
}
if(lines >= j * 2)
{
System.out.print(spaces);
}
for (k = lines ; k >= j * 2; k--)
{
System.out.print(character);
}
if (lines >= j * 2)
{
System.out.println();
}
}

Beginner in Java - Controlling output - Generating Asterix

I am having difficulties with completing this program. I am trying to make a program that creates asteriks, but then makes it into a triangle.
This is what I have already.
public class 12345 {
public static void main(String[] args) {
int n = 0;
int spaces = n;
int ast;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
n = keyboard.nextInt();
for (int i = 0; i < n; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces)
System.out.print(' ');
else
System.out.print('*');
}
System.out.println();
spaces--;
}
}
}
It is creating the asteriks, but how would I be able to continue them where they make a triangle... so they get bigger as they go, and then back smaller...
Thank you in advance!
Try moving
int spaces = n;
to AFTER the value of n is read from stdin.
This solves half your problem and hopefully gets you on the right track.
I added a few things to your code and got it to print the full triangle, where the number input in the scanner will be the number of asterisks printed in the bottom row. I.e. if the input is 3, the triangle will be two rows of 1->3; if the input is 5 then the triangle will be 3 rows of 1->3->5, and so on.
public static void main(String[] args) {
int ast;
int reverse = 1;
System.out.println("Please enter a number from 1 - 50 and I will draw a triangle with these *");
Scanner keyboard = new Scanner(System.in);
int spaces = keyboard.nextInt();
for (int i = 0; i < spaces; i++) {
ast = 2 * i + 1;
for (int j = 1; j <= spaces + ast; j++) {
if (j <= spaces) {
System.out.print(' ');
} else {
System.out.print('*');}
if (j > spaces + ast) {
for (int k = 0; k < spaces-(reverse-1); k++) {
System.out.print(' ');
}
}
int k = 0;
reverse++;
}
System.out.println();
spaces--;
}
}
}
I added another if statement after your if-else that triggers when the variable j exceeds the first loop condition. This triggers another loop that makes the output lines symmetrical by essentially repeating your first if statement.
I hope this helps =)

Categories

Resources